错误“无法访问“DataFrameGroupBy"对象的可调用属性“sample",请尝试使用“apply"方法" [英] Error "Cannot access callable attribute 'sample' of 'DataFrameGroupBy' objects, try using the 'apply' method"

查看:144
本文介绍了错误“无法访问“DataFrameGroupBy"对象的可调用属性“sample",请尝试使用“apply"方法"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模拟数据:

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 的附加索引.

<预><代码>>>>df.groupby('country', group_keys=False).apply(lambda df: df.sample(1))身份证件国家6 7 加拿大2 3 美国

似乎是 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屋!

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