在应用函数pandas python中包含组名 [英] Including the group name in the apply function pandas python

查看:20
本文介绍了在应用函数pandas python中包含组名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以指定 groupby() 调用在 apply() lambda 函数中使用组名?

Is there away to specify to the groupby() call to use the group name in the apply() lambda function?

类似于如果我遍历组,我可以通过以下元组分解获得组键:

Similar to if I iterate through groups I can get the group key via the following tuple decomposition:

for group_name, subdf in temp_dataframe.groupby(level=0, axis=0):
    print group_name

...有没有办法在apply函数中也得到组名,比如:

...is there a way to also get the group name in the apply function, such as:

temp_dataframe.groupby(level=0,axis=0).apply(lambda group_name, subdf: foo(group_name, subdf)

如何获取组名作为 apply lambda 函数的参数?

How can I get the group name as an argument for the apply lambda function?

推荐答案

我认为你应该可以使用 name 属性:

I think you should be able to use the nameattribute:

temp_dataframe.groupby(level=0,axis=0).apply(lambda x: foo(x.name, x))

应该可以,例如:

In [132]:
df = pd.DataFrame({'a':list('aabccc'), 'b':np.arange(6)})
df

Out[132]:
   a  b
0  a  0
1  a  1
2  b  2
3  c  3
4  c  4
5  c  5

In [134]:
df.groupby('a').apply(lambda x: print('name:', x.name, '\nsubdf:',x))

name: a 
subdf:    a  b
0  a  0
1  a  1
name: b 
subdf:    a  b
2  b  2
name: c 
subdf:    a  b
3  c  3
4  c  4
5  c  5
Out[134]:
Empty DataFrame
Columns: []
Index: []

这篇关于在应用函数pandas python中包含组名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆