Python pandas groupby 聚合

Alc*_*ott 3 python group-by aggregation pandas

我有一个DataFrame df, 组成(age, height). 我想看看身高的平均值如何随年龄变化,所以我分组dfage尝试形成一个新的由DataFrame new_df组成,(age, mean_height)代码如下:

groups = df.groupby('age')
new_df = groups.agg({'height' : np.mean,
                     'age' : # HOW to add age?})
Run Code Online (Sandbox Code Playgroud)

但我不知道如何附加agenew_df希望有人能给我一些建议。

Kor*_*rem 6

Age 是聚合数据帧的索引:

In [95]: df = DataFrame({'age':[10,10,20,20,20], 'height':[140,150,145, 190,200]})

In [96]: df
Out[96]: 
   age  height
0   10     140
1   10     150
2   20     145
3   20     190
4   20     200

In [97]: groups = df.groupby('age')

In [98]: groups.agg({'height':np.mean})
Out[98]: 
         height
age            
10   145.000000
20   178.333333
Run Code Online (Sandbox Code Playgroud)

并且df.groupby('age').mean()会达到同样的结果。如果您希望将其作为列而不是索引,请添加对 的调用reset_index()

作为替代方案,您可以调用groupbywith as_index=False

groups = df.groupby('age', as_index=False)
groups.agg({'heigt': np.mean})
Run Code Online (Sandbox Code Playgroud)