Python用相同的键对Dataframe中的行求和

mrs*_*uid 5 python statistics numpy pandas data-cleaning

我想总结数据框中具有相同行键的行。

目的是缩小数据集的大小。

例如,如果数据框看起来像这样。

Fruit       Count

Apple         10

Pear          20

Apple          5

Banana         7

Banana         12

Pear           8  

Apple          10
Run Code Online (Sandbox Code Playgroud)

我希望最终的数据框看起来像这样。

Fruit       Count

Apple         25

Pear          28

Banana        19
Run Code Online (Sandbox Code Playgroud)

我正在使用Python的pandas、numpy、matplotlib和其他数据分析包。有没有办法在 python 中使用这些包中的函数来做到这一点?

这是创建示例数据框的代码。

df = pd.DataFrame([["Apple", 10], ["Pear", 20], ["Apple", 5], ["Banana", 7], ["Banana", 12], ["Pear", 8], ["Apple", 10]], columns=["Fruit", "Count"])
Run Code Online (Sandbox Code Playgroud)

U10*_*ard 5

groupbyas_index=False, 和 一起使用sum

>>> df.groupby('Fruit',as_index=False)['Count'].sum()
    Fruit  Count
0   Apple     25
1  Banana     19
2    Pear     28
>>> 
Run Code Online (Sandbox Code Playgroud)


Alw*_*nny 4

groupby与怎么样sum()?例如df.groupby(['Fruit'])['Count'].sum()

import pandas as pd
df = pd.DataFrame([["Apple", 10], ["Pear", 20], ["Apple", 5], ["Banana", 7], ["Banana", 12], ["Pear", 8], ["Apple", 10]], columns=["Fruit", "Count"])
df = df.groupby(['Fruit'])['Count'].sum()
print(df)
Run Code Online (Sandbox Code Playgroud)

输出:

Fruit
Apple     25
Banana    19
Pear      28
Run Code Online (Sandbox Code Playgroud)