Pandas groupby意味着 - 进入数据帧?

时间:2017-10-25 17:28:15

标签: pandas group-by

说我的数据如下:

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正确引用。

4 个答案:

答案 0 :(得分:14)

如果您在系列中调用.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

答案 1 :(得分:2)

添加to_frame

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

答案 2 :(得分:2)

你非常接近。您只需要在[['total_sale']]周围添加一组括号,告诉python选择数据帧而不是系列:

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

如果您想要所有列:

df.groupby(['name', 'id', 'dept'], as_index=False).mean()[['name', 'id', 'dept', 'total_sale']]

答案 3 :(得分:0)

答案是两行代码:

第一行创建层次框架。

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

第二行将其转换为具有四列('name','id','dept','total_sale')的数据框

df_mean = df_mean.reset_index()