Python Dataframe Groupby Mean and STD

Viewed 421

I know how to compute the groupby mean or std. But now I want to compute both at a time. My code:

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()])

Present output:

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

Try to remove () from the np. functions:

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

Prints:

          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

EDIT: To "flatten" column multi-index:

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

Prints:

        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
Related