Skip to content Skip to sidebar Skip to footer

Python Dataframe Groupby Mean And Std

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

Solution 1:

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

Post a Comment for "Python Dataframe Groupby Mean And Std"