Pandas mean for certain columns (binary values) based on another column

Viewed 358

Suppose we have something like this:

df = pd.DataFrame([[0,1,0,13], [1,0,1,14], [1,1,0,12], [1,0,0,15]], columns = ["A", "B" , "C", "p"])

A, B, C have binary values and I want to compute mean of p for each column, but for each group (1 and 0) separately.

For one column I use

df.groupby('A')['p'].mean()

But how to compute mean for columns ABC at once?

1 Answers

Use DataFrame.melt for unpivot first, aggregate mean and last add Series.unstack:

df1 = df.melt('p').groupby(['variable', 'value'])['p'].mean().unstack(fill_value=0)

Or use DataFrame.pivot_table:

df1 = df.melt('p').pivot_table(index='variable', columns='value', values='p', fill_value=0)

print (df1)
value             0          1
variable                      
A         13.000000  13.666667
B         14.500000  12.500000
C         13.333333  14.000000
Related