[英]How to access group keys during aggregation in pandas groupby?
Is there a way to access the group keys from inside the aggregation functions?有没有办法从聚合函数内部访问组键? For example we have the following dataframe:
例如,我们有以下数据框:
>>> df = pd.DataFrame({
'score' : [2,2,3,3,3],
'age' : [17,23,18,12,15]
})
>>> df
score age
0 2 17
1 2 23
2 3 18
3 3 12
4 3 15
And do something like并做类似的事情
df.groupby('score').agg(
score_age = ('age', lambda x: x.groupkey + sum(x))
)
to get要得到
score_age
score
2 42
3 48
Obviously x.groupkey
does not work.显然
x.groupkey
不起作用。 What's the right syntax to access it?访问它的正确语法是什么? I can't seem to find it anywhere.
我似乎无法在任何地方找到它。 Please help.
请帮忙。
Use:利用:
df1 = df.groupby('score').agg(score_age = ('age', lambda x: x.name + x.sum()))
print (df1)
score_age
score
2 42
3 48
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.