gpt4 book ai didi

python - Pandas groupby mean - 进入数据框?

转载 作者:行者123 更新时间:2023-12-04 09:06:10 24 4
gpt4 key购买 nike

假设我的数据如下所示:

date,name,id,dept,sale1,sale2,sale3,total_sale
1/1/17,John,50,Sales,50.0,60.0,70.0,180.0
1/1/17,Mike,21,Engg,43.0,55.0,2.0,100.0
1/1/17,Jane,99,Tech,90.0,80.0,70.0,240.0
1/2/17,John,50,Sales,60.0,70.0,80.0,210.0
1/2/17,Mike,21,Engg,53.0,65.0,12.0,130.0
1/2/17,Jane,99,Tech,100.0,90.0,80.0,270.0
1/3/17,John,50,Sales,40.0,50.0,60.0,150.0
1/3/17,Mike,21,Engg,53.0,55.0,12.0,120.0
1/3/17,Jane,99,Tech,80.0,70.0,60.0,210.0

我想要一个新专栏 average ,这是 total_sale 的平均值对于每个 name,id,dept元组

我试过
df.groupby(['name', 'id', 'dept'])['total_sale'].mean()

这确实返回了一个具有平均值的系列:
name  id  dept 
Jane 99 Tech 240.000000
John 50 Sales 180.000000
Mike 21 Engg 116.666667
Name: total_sale, dtype: float64

但我将如何引用数据?该系列是形状 (3,) 的一维系列。理想情况下,我希望将其放回具有适当列的数据框中,以便我可以通过 name/id/dept 正确引用.

最佳答案

如果您调用.reset_index()在您拥有的系列上,它将为您提供所需的数据框(索引的每个级别都将转换为一列):

df.groupby(['name', 'id', 'dept'])['total_sale'].mean().reset_index()

编辑:为了回应 OP 的评论,将此列添加回您的原始数据框有点棘手。您的行数与原始数据框中的行数不同,因此您还不能将其分配为新列。但是,如果您将索引设置为相同, pandas很聪明,会为您正确填写值。试试这个:
cols = ['date','name','id','dept','sale1','sale2','sale3','total_sale']
data = [
['1/1/17', 'John', 50, 'Sales', 50.0, 60.0, 70.0, 180.0],
['1/1/17', 'Mike', 21, 'Engg', 43.0, 55.0, 2.0, 100.0],
['1/1/17', 'Jane', 99, 'Tech', 90.0, 80.0, 70.0, 240.0],
['1/2/17', 'John', 50, 'Sales', 60.0, 70.0, 80.0, 210.0],
['1/2/17', 'Mike', 21, 'Engg', 53.0, 65.0, 12.0, 130.0],
['1/2/17', 'Jane', 99, 'Tech', 100.0, 90.0, 80.0, 270.0],
['1/3/17', 'John', 50, 'Sales', 40.0, 50.0, 60.0, 150.0],
['1/3/17', 'Mike', 21, 'Engg', 53.0, 55.0, 12.0, 120.0],
['1/3/17', 'Jane', 99, 'Tech', 80.0, 70.0, 60.0, 210.0]
]
df = pd.DataFrame(data, columns=cols)

mean_col = df.groupby(['name', 'id', 'dept'])['total_sale'].mean() # don't reset the index!
df = df.set_index(['name', 'id', 'dept']) # make the same index here
df['mean_col'] = mean_col
df = df.reset_index() # to take the hierarchical index off again

关于python - Pandas groupby mean - 进入数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46938572/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com