Python Dataframe Groupby Mean和Std

2022-02-26 00:00:00 python numpy dataframe pandas-groupby mean

问题描述

我知道如何计算GROUP BY平均值或STD。但现在我想同时计算两者。 我的代码:

df = 
   a      b      c      d
0  Apple  3      5      7
1  Banana 4      4      8
2  Cherry 7      1      3
3  Apple  3      4      7

xdf = df.groupby('a').agg([np.mean(),np.std()])

当前输出:

TypeError: _mean_dispatcher() missing 1 required positional argument: 'a'

解决方案

尝试从np.函数中删除()

xdf = df.groupby("a").agg([np.mean, np.std])
print(xdf)

打印:

          b         c              d     
       mean  std mean       std mean  std
a                                        
Apple     3  0.0  4.5  0.707107    7  0.0
Banana    4  NaN  4.0       NaN    8  NaN
Cherry    7  NaN  1.0       NaN    3  NaN

编辑:展平列多索引(&Q;T):

xdf = df.groupby("a").agg([np.mean, np.std])
xdf.columns = xdf.columns.map("_".join)
print(xdf)

打印:

        b_mean  b_std  c_mean     c_std  d_mean  d_std
a                                                     
Apple        3    0.0     4.5  0.707107       7    0.0
Banana       4    NaN     4.0       NaN       8    NaN
Cherry       7    NaN     1.0       NaN       3    NaN

相关文章