简体   繁体   中英

Pandas Groupby - naming aggregate output column

I have a pandas groupby command which looks like this:

df.groupby(['year', 'month'], as_index=False).agg({'users':sum})

Is there a way I can name the agg output something other than 'users' during the groupby command? For example, what if I wanted the sum of users to be total_users? I could rename the column after the groupby is complete, but wonder if there is another way.

Per the docs :

If a dict is passed, the keys will be used to name the columns. Otherwise the function's name (stored in the function object) will be used.

In [58]: grouped['D'].agg({'result1' : np.sum, ....:
'result2' : np.mean})

In your case:

df.groupby(['year', 'month'], as_index=False).users.agg({'total_users': np.sum})

我喜欢@Alexander的答案,但也有add_prefix

df.groupby(['year','month']).agg({'users':sum}).add_prefix('total_')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM