如何将列从一个数据框合并到另一个数据框

时间:2018-08-14 11:14:49

标签: python pandas

如何将列从数据框合并到多索引数据框标头。

即如何合并各个主题值并创建新的数据框

        import pandas as pd
        import numpy as np

        df = pd.DataFrame({'Maths':[95,96,97,98] ,'Science': [91,92,93,94]})
        df1 = pd.DataFrame({'Social':[85,86,87,88] ,'English': [81,82,83,84]})
        print df 
       Maths  Science
    0     95       91
    1     96       92
    2     97       93
    3     98       94
    print df1
       English  Social
    0       81      85
    1       82      86
    2       83      87
    3       84      88

1 个答案:

答案 0 :(得分:5)

concat与参数keys一起使用:

df = pd.concat([df, df1], axis=1, keys=('Semester1','Semester2'))
print (df)
  Semester1         Semester2        
      Maths Science    Social English
0        95      91        85      81
1        96      92        86      82
2        97      93        87      83
3        98      94        88      84

print (df.columns)
MultiIndex(levels=[['Semester1', 'Semester2'], ['English', 'Maths', 'Science', 'Social']],
           labels=[[0, 0, 1, 1], [1, 2, 3, 0]])

编辑:对于新列,请使用assign

df = df.assign(avg=df.mean(axis=1), perc=df.sum(axis=1) / df.values.sum())
df1 = df.assign(avg=df1.mean(axis=1),perc=df1.sum(axis=1) / df1.values.sum())

df = pd.concat([df, df1], axis=1, keys=('Semester1','Semester2'))
print (df)
  Semester1                         Semester2                        
      Maths Science   avg      perc     Maths Science   avg      perc
0        95      91  93.0  0.246032        95      91  83.0  0.245562
1        96      92  94.0  0.248677        96      92  84.0  0.248521
2        97      93  95.0  0.251323        97      93  85.0  0.251479
3        98      94  96.0  0.253968        98      94  86.0  0.254438