Pandas .groups AttributeError: 'DataFrame' has no attribute 'groups

Pandas .groups AttributeError: 'DataFrame' has no attribute 'groups

我有一个分组的 DataFrame,我想获取这些组以便稍后迭代它们,但是 .groups 正在返回 AttributeError: 'DataFrame' object has no attribute 'groups'

test = temp.groupby(['global company key','calendar year'])[['columnA','columnB', 'columnC']].sum()

数据示例:

                                   columnA     columnB     columnC
global company key  calendar year  
          1109          2010            20          30          20
          1109          2011            11          10          13
          1468          2010            50          10          16
          1468          2011             1           3           7

我试过的运行:

test.groups

我是不是做错了什么?从文档来看,这应该非常简单。

使用 group by 时,返回的对象是一个 GroupBy 对象,它具有您使用的 groups 属性。但是当在 Groupby 对象(在你的例子中是 sum() )上应用任何函数时,它会变回 pd.DataFrame ,它没有 .groups.

另一种方法是将您的数据框转换为可迭代对象(例如df.to_dict(),然后对其进行迭代。