Pandas Groupby - 命名聚合输出列 [英] Pandas Groupby - naming aggregate output column
问题描述
我有一个 pandas
groupby
命令,如下所示:
I have a pandas
groupby
command which looks like this:
df.groupby(['year', 'month'], as_index=False).agg({'users':sum})
有什么方法可以在 groupby 命令期间将 agg
输出命名为users"以外的其他名称?例如,如果我希望用户总数为 total_users 怎么办?我可以在 groupby 完成后重命名该列,但想知道是否还有其他方法.
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.
推荐答案
根据 文档:
如果传递了 dict,则键将用于命名列.否则函数的名称(存储在函数对象中)将是用过.
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.
在[58]中:grouped['D'].agg({'result1': np.sum, ....:
'result2':np.mean})
In [58]: grouped['D'].agg({'result1' : np.sum, ....:
'result2' : np.mean})
就你而言:
df.groupby(['year', 'month'], as_index=False).users.agg({'total_users': np.sum})
这篇关于Pandas Groupby - 命名聚合输出列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!