【问题标题】:Pandas reset_index() is not working after grouping by and aggregating by multiple methodsPandas reset_index() 在通过多种方法分组和聚合后不起作用
【发布时间】:2019-04-23 22:17:42
【问题描述】:

我有一个带有 2 个分组列和 3 个数字列的 pandas DataFrame。 我将数据分组如下:

df = df.groupby(['date_week', 'uniqeid']).agg({
    'completes':['sum', 'median', 'var', 'min', 'max']
    ,'dcount_visitors': ['sum', 'median', 'var', 'min', 'max']
     ,'dcount_visitor_groups': ['sum', 'median', 'var', 'min', 'max']
     })

结果是预期的多级索引:

MultiIndex(levels=[['completes', 'dcount_visitors', 'dcount_subscriptions', 'dcount_visitor_groups', 'date_week'], ['sum', 'median', 'var', 'min', 'max', '']],
           labels=[[4, 3, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2], [5, 5, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4]])

通常我会像这样展平多索引:

df2 = df2.reset_index(drop=True)

但是,当我检查列时,我仍然得到一个多索引。 我已经尝试在我的 groupby 函数中包含 as_index=False ,但这也不起作用。

有趣的是,如果我只使用 1 个数字列和一个聚合,则此过程按预期工作。

u = nunits.groupby(['account', 'week_date', 'accountid', 'full_account_name','SegmentName'], as_index=False).agg({'ConsumptionUnit': 'sum'})

Index(['account', 'week_date', 'accountid', 'full_account_name', 'SegmentName',
       'ConsumptionUnit'],
      dtype='object')

任何提示或建议将不胜感激。

【问题讨论】:

  • 你试过df2.columns = df2.columns.get_level_values(0) 吗?
  • 即使加了[]agg({'ConsumptionUnit': ['sum']})只有一个值,它仍然是列中的多个索引,这就是它的工作原理

标签: python pandas feature-engineering


【解决方案1】:

(意识到“接受”自己的问题有点违反规范,但希望节省人们回答已解决问题的时间)

@Efran:我做到了,它是一个 2 级多索引。 @Bugbeeb:很好地确定级别。标签上的 5 让我失望。

我找到了答案:从 Pandas 0.24.0 开始,您可以使用 .to_flat_index。 我一直在使用 0.23.0,所以在该文档中没有找到这个选项。

可以在here找到如何使用它的示例

之后:df.columns = df.columns.to_flat_index() 结果索引如下所示

Index([                                   'date_week',
                                               'TPID',
                              ('completes', 'sum'),
                           ('completes', 'median'),
                              ('completes', 'var'),
                              ('completes', 'min'),
                              ('completes', 'max'),
          ('dcount_visitors_with_events', 'sum'),
       ('dcount_visitors_with_events', 'median'),
          ('dcount_visitors_with_events', 'var'),
          ('dcount_visitors_with_events', 'min'),
          ('dcount_visitors_with_events', 'max'),
                      ('dcount_id_groups', 'sum'),
                   ('dcount_id_groups', 'median'),
                      ('dcount_id_groups', 'var'),
                      ('dcount_id_groups', 'min'),
                      ('dcount_id_groups', 'max')],
      dtype='object')

希望这对其他人有所帮助,并感谢您的快速回复。 这个社区很棒!

【讨论】:

    【解决方案2】:

    您需要在 multi_index (0,1,2,3...) 中识别级别。并使用 inplace=True 而不是重新分配 df

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-03
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      • 1970-01-01
      • 2017-02-27
      • 2016-05-04
      • 1970-01-01
      相关资源
      最近更新 更多