错误“无法访问“DataFrameGroupBy"对象的可调用属性“sample",请尝试使用“apply"方法" [英] Error "Cannot access callable attribute 'sample' of 'DataFrameGroupBy' objects, try using the 'apply' method"
问题描述
模拟数据:
df = pd.DataFrame({'id': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],'国家':['美国','美国','美国','美国','美国','加拿大','加拿大','加拿大','美国','加拿大']})
假设我想为每个国家/地区抽取一个观察结果:
df.groupby('country').sample(1)
我收到此错误:
AttributeError: 无法访问DataFrameGroupBy"对象的可调用属性sample",请尝试使用apply"方法
我尝试重置索引,但没有解决问题.我也试过这里的答案,它没有工作.我做错了什么?
这个问题有后续此处.
根据错误使用 apply()
.group_keys=False
将删除 country
的附加索引.
似乎是 Pandas 版本不匹配,因为 groupby
是在 version 1.1.0
中引入的.我运行了 OPs 代码,它也能正常工作.
您需要使用 pip3 install --upgrade pandas
Mock data:
df = pd.DataFrame({
'id': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'country': ['USA', 'USA', 'USA', 'USA', 'USA', 'Canada', 'Canada', 'Canada', 'USA', 'Canada']
})
Let's say I want to sample one observation for each country:
df.groupby('country').sample(1)
I get this error:
AttributeError: Cannot access callable attribute 'sample' of 'DataFrameGroupBy' objects, try using the 'apply' method
I have tried to reset the index, it didn't solve the problem. I have also tried the answer here, it didn't work. What am I doing wrong?
EDIT: this question has a follow up here.
As the per the error use apply()
. group_keys=False
will remove the additional index of country
.
>>> df.groupby('country', group_keys=False).apply(lambda df: df.sample(1))
id country
6 7 Canada
2 3 USA
Edit:
Seems to be a mismatch of Pandas versions as groupby
was introduced in version 1.1.0
. I ran the OPs code and it works as well.
You will need to upgrade pandas using pip3 install --upgrade pandas
这篇关于错误“无法访问“DataFrameGroupBy"对象的可调用属性“sample",请尝试使用“apply"方法"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!