是否可以groupby()
在apply()
lambda函数中指定使用组名的调用?
类似于如果我遍历组,则可以通过以下元组分解来获取组密钥:
for group_name, subdf in temp_dataframe.groupby(level=0, axis=0):
print group_name
...是否有一种方法也可以在apply函数中获取组名,例如:
temp_dataframe.groupby(level=0,axis=0).apply(lambda group_name, subdf: foo(group_name, subdf)
如何获取组名称作为apply lambda函数的参数?
我认为您应该能够使用该name
属性:
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: []
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句