Pandas Groupby: Count and mean combined
In newer versions of pandas you don't need the rename anymore, just use named aggregation:
df = df.groupby('source') \
.agg(count=('text', 'size'), mean_sent=('sent', 'mean')) \
.reset_index()
print (df)
source count mean_sent
0 bar 2 0.415
1 foo 3 -0.500
You can use groupby
with aggregate
:
df = df.groupby('source') \
.agg({'text':'size', 'sent':'mean'}) \
.rename(columns={'text':'count','sent':'mean_sent'}) \
.reset_index()
print (df)
source count mean_sent
0 bar 2 0.415
1 foo 3 -0.500
Below one should work fine:
df[['source','sent']].groupby('source').agg(['count','mean'])