【问题标题】:Convert an indexed pandas matrix to a flat dataframe将索引熊猫矩阵转换为平面数据框
【发布时间】:2017-08-27 19:31:13
【问题描述】:

给定数据框:

df = pd.DataFrame([['foo', 123, 4, 5, 0, 1], ['foo', 123, 4, 0, 9, 1], ['bar', 33, 0, 0, 3, 5]], columns=list('ABCDEF'))

[出]:

    A   B   C   D   E   F
0   foo 123 4   5   0   1
1   foo 123 4   0   9   1
2   bar 33  0   0   3   5

目标是使用其他列('A'和'B')作为键来对某些列('C'、'D'、'E'、F')求和以实现:

    A   B   C   D   E   F
0   foo 123 8   5   9   2
2   bar 33  0   0   3   5

我试过了:

df.groupby(['A', 'B']).sum()

[出]:

        C   D   E   F
A   B               
bar 33  0   0   3   5
foo 123 8   5   9   2

如何将它改回非索引矩阵?即

    A   B   C   D   E   F
0   foo 123 8   5   9   2
2   bar 33  0   0   3   5

【问题讨论】:

    标签: pandas dataframe indexing group-by


    【解决方案1】:

    您需要添加.reset_index()

    df.groupby(['A','B']).sum().reset_index()
    
        A   B   C   D   E   F
    0   bar 33  0   0   3   5
    1   foo 123 8   5   9   2
    

    df.set_index(['A','B']).sum(level=[0,1]).reset_index()
    
        A   B   C   D   E   F
    0   bar 33  0   0   3   5
    1   foo 123 8   5   9   2
    

    【讨论】:

      【解决方案2】:

      您可以使用参数as_index=False 来返回df

      df1 = df.groupby(['A', 'B'], as_index=False).sum()
      print (df1)
           A    B  C  D  E  F
      0  bar   33  0  0  3  5
      1  foo  123  8  5  9  2
      

      【讨论】:

        猜你喜欢
        • 2021-12-14
        • 2020-12-09
        • 2019-09-28
        • 2020-02-13
        • 2019-04-27
        • 1970-01-01
        • 1970-01-01
        • 2013-12-26
        相关资源
        最近更新 更多