panda dataframe groupby mean on a column code example
Example 1: pandas calculate mean by groups
df.groupby('column_name').mean()
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': [1, 1, 2, 1, 2],
'B': [np.nan, 2, 3, 4, 5],
'C': [1, 2, 1, 1, 2]}, columns=['A', 'B', 'C'])
print(df)
A B C
0 1 NaN 1
1 1 2.0 2
2 2 3.0 1
3 1 4.0 1
4 2 5.0 2
df.groupby('A').mean()
B C
A
1 3.0 1.333333
2 4.0 1.500000
df.groupby(['A', 'B']).mean()
C
A B
1 2.0 2
4.0 1
2 3.0 1
5.0 2
Example 2: pandas groupby mean
df.groupby(['A', 'B']).mean()