【问题标题】:Multilevel concatenation grouped by a common index (pandas)由公共索引(熊猫)分组的多级串联
【发布时间】:2022-10-24 16:51:10
【问题描述】:

我正在尝试将多个数据框合并为一个。我需要组合数据框具有多级标题,如下例所示。我还需要将数据框分组在多个索引列上。

我已经看到了上述某些部分的答案,但没有结合起来,我无法弄清楚。

我真的很感激一些帮助!

'一个'

                                   'a' 'b'        
'index1.1'  'index1.2'  'index1.3'  9   8
'index2.1'  'index2.2'  'index2.3'  6   3
'index3.1'  'index3.2'  'index3.3'  8   4
'index4.1'  'index4.2'  'index4.3'  5   7
'index5.1'  'index5.2'  'index5.3'  3   8 

'乙'

                                   'a' 'b'        
'index1.1'  'index1.2'  'index1.3'  6   2
'index2.1'  'index2.2'  'index2.3'  4   7
'index3.1'  'index3.2'  'index3.3'  1   5
'index4.1'  'index4.2'  'index4.3'  4   7
'index5.1'  'index5.2'  'index5.3'  3   6 

'C'

                                   'b' 'c'        
'index1.1'  'index1.2'  'index1.3'  3   0
'index2.1'  'index2.2'  'index2.3'  2   1
'index3.1'  'index3.2'  'index3.3'  1   5
'index4.1'  'index4.2'  'index4.3'  6   7
'index5.1'  'index5.2'  'index5.3'  3   1 

组合数据框:

                                   'A' 'A' 'B' 'B' 'C' 'C'
                                   'a' 'b' 'a' 'b' 'b' 'c'      
'index1.1'  'index1.2'  'index1.3'  9   8   6   2   3   0
'index2.1'  'index2.2'  'index2.3'  6   3   4   7   2   1
'index3.1'  'index3.2'  'index3.3'  8   4   1   5   1   5
'index4.1'  'index4.2'  'index4.3'  5   7   4   7   6   7
'index5.1'  'index5.2'  'index5.3'  3   8   3   6   3   1

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    利用:

    df = pd.concat([A, B, C], axis=1, keys=('A','B','C'))
    print (df)
                                       A       B       C    
                                     'a' 'b' 'a' 'b' 'b' 'c'
    'index1.1' 'index1.2' 'index1.3'   9   8   6   2   3   0
    'index2.1' 'index2.2' 'index2.3'   6   3   4   7   2   1
    'index3.1' 'index3.2' 'index3.3'   8   4   1   5   1   5
    'index4.1' 'index4.2' 'index4.3'   5   7   4   7   6   7
    'index5.1' 'index5.2' 'index5.3'   3   8   3   6   3   1
    

    【讨论】:

      猜你喜欢
      • 2019-05-26
      • 2019-05-03
      • 1970-01-01
      • 2017-06-03
      • 1970-01-01
      • 2016-10-16
      • 2019-01-19
      • 2017-06-08
      • 1970-01-01
      相关资源
      最近更新 更多