Ich*_*san 3 python sum dataframe pandas
请帮助我,例如,如何使用带有一些列的总和和一些列的平均值的 Pandas groupby。我有一个名为“市场”的数据框:
product quantity sell_price profit
0 bread 2 5 10
1 bread 3 4 12
2 bread 1 3 3
3 milk 3 2 6
4 milk 2 1 2
Run Code Online (Sandbox Code Playgroud)
可重现的例子:
df = pd.DataFrame({'product': ['bread', 'bread', 'bread', 'milk', 'milk'],
'quantity': [2, 3, 1,3,2],
'sell_price': [5,4,3,2,1],
'profit': [10,12,3,6,2]})
Run Code Online (Sandbox Code Playgroud)
像这样摆桌子
[Product][quantity][sell_price][profit]
[bread][6][4][25]
[milk][5][1,5][8]
Run Code Online (Sandbox Code Playgroud)
其中,sell_price 是每种产品的平均值,数量是每种产品的总和,而利润是每种产品的总和
我已经做过的
market.groupby('product').sum('quantity,'profit').mean('sell_price')
Run Code Online (Sandbox Code Playgroud)
使用pandas.DataFrame.groupby.agg
:
new_df = df.groupby('Product').agg({'quantity':'sum', 'profit': 'sum', 'sell_price': 'mean'})
print(new_df)
Run Code Online (Sandbox Code Playgroud)
输出:
quantity profit sell_price
Product
bread 6 25 4.0
milk 5 8 1.5
Run Code Online (Sandbox Code Playgroud)