【问题标题】:How to calculate count and percentage in groupby in Python如何在 Python 中计算 groupby 中的计数和百分比
【发布时间】:2017-02-15 00:44:23
【问题描述】:

分组后有以下输出

Publisher.groupby('Category')['Title'].count()
Category
Coding          5
Hacking         7
Java            1
JavaScript      5
LEGO           43
Linux           7
Networking      5
Others        123
Python          8
R               2
Ruby            4
Scripting       4 
Statistics      2
Web             3

在上面的输出中,我还想要百分比,即第一行 5*100/219 等等。我正在关注

 Publisher.groupby('Category')['Title'].agg({'Count':'count','Percentage':lambda x:x/x.sum()})

但它给了我一个错误。请帮忙

【问题讨论】:

标签: python pandas group-by


【解决方案1】:

我认为你可以使用:

P = Publisher.groupby('Category')['Title'].count().reset_index()
P['Percentage'] = 100 * P['Title']  / P['Title'].sum()

示例:

Publisher = pd.DataFrame({'Category':['a','a','s'],
                   'Title':[4,5,6]})

print (Publisher)
  Category  Title
0        a      4
1        a      5
2        s      6

P = Publisher.groupby('Category')['Title'].count().reset_index()
P['Percentage'] = 100 * P['Title']  / P['Title'].sum()
print (P)
  Category  Title  Percentage
0        a      2   66.666667
1        s      1   33.333333

【讨论】:

  • 太棒了。它确实有效。我想知道我们是否可以在 groupby 中执行此操作,然后在 agg 中应用 count and percentage 函数?
  • 嗯,可能通过Edchum检查链接,但我认为这是有问题的,因为你返回Series,所以错误Exception: Must produce aggregated value。我不确定。
【解决方案2】:
df = pd.DataFrame({'Category':['a','a','s'],
                   'Title':[4,5,6]})

df=df.groupby('Category')['Title'].count().rename("percentage").transform(lambda x: x/x.sum())

df.reset_index()

#output in dataframe type

    Category    percentage
0   a   0.666667
1   s   0.333333

#please let me know if it doesn't solve your current problem

【讨论】:

    猜你喜欢
    • 2022-06-23
    • 2022-11-21
    • 2020-09-21
    • 2022-06-13
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 2021-02-20
    相关资源
    最近更新 更多