错误 "Cannot access callable attribute 'sample' of 'DataFrameGroupBy' objects, try using the 'apply' method"

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],
        'country': ['USA', 'USA', 'USA', 'USA', 'USA', 'Canada', 'Canada', 'Canada', 'USA', 'Canada']
})

假设我想对每个国家抽样一次观察:

df.groupby('country').sample(1)

我收到这个错误:

AttributeError: Cannot access callable attribute 'sample' of 'DataFrameGroupBy' objects, try using the 'apply' method

我已经尝试重置索引,但没有解决问题。 这个答案我也试过了,没用。我做错了什么?

编辑:这个问题有跟进

根据错误使用 apply()group_keys=False 将删除 country 的附加索引。

>>> df.groupby('country', group_keys=False).apply(lambda df: df.sample(1))
   id country
6   7  Canada
2   3     USA

编辑: 似乎 Pandas 版本不匹配,因为 groupby 是在 version 1.1.0 中引入的。我 运行 OP 代码,它也能正常工作。

您需要使用 pip3 install --upgrade pandas

升级 pandas