Skip to content Skip to sidebar Skip to footer

Pandas Groupby Two Columns And Summarize By Mean

I have a data frame like this: df = pd.DataFrame() df['id'] = [1,1,1,2,2,3,3,3,3,4,4,5] df['view'] = ['A', 'B', 'A', 'A','B', 'A', 'B', 'A', 'A','B', 'A', 'B'] df['value'] = np.ran

Solution 1:

You need reset_index or parameter as_index=False in groupby, because you get MuliIndex and by default the higher levels of the indexes are sparsified to make the console output a bit easier on the eyes:

np.random.seed(100)
df = pd.DataFrame()
df['id'] = [1,1,1,2,2,3,3,3,3,4,4,5]
df['view'] = ['A', 'B', 'A', 'A','B', 'A', 'B', 'A', 'A','B', 'A', 'B']
df['value'] = np.random.random(12)
print (df)
    id view     value
0    1    A  0.543405
1    1    B  0.278369
2    1    A  0.424518
3    2    A  0.844776
4    2    B  0.004719
5    3    A  0.121569
6    3    B  0.670749
7    3    A  0.825853
8    3    A  0.136707
9    4    B  0.575093
10   4    A  0.891322
11   5    B  0.209202
res = df.groupby(['id', 'view'])['value'].mean().reset_index()
print (res)
   id view     value
0   1    A  0.483961
1   1    B  0.278369
2   2    A  0.844776
3   2    B  0.004719
4   3    A  0.361376
5   3    B  0.670749
6   4    A  0.891322
7   4    B  0.575093
8   5    B  0.209202

res = df.groupby(['id', 'view'], as_index=False)['value'].mean()
print (res)
   id view     value
0   1    A  0.483961
1   1    B  0.278369
2   2    A  0.844776
3   2    B  0.004719
4   3    A  0.361376
5   3    B  0.670749
6   4    A  0.891322
7   4    B  0.575093
8   5    B  0.209202

Post a Comment for "Pandas Groupby Two Columns And Summarize By Mean"