使用pandas

时间:2017-06-19 12:37:54

标签: python pandas

我有两个数据帧,如下面的多级索引:

DF1:

    Total_Consumption
    2010        2011        2012
1   8544.357    5133.553    5279.884
2   8581.545    6091.454    4323.611
3   4479.319    2784.283    1948.262
4   5493.114    3633.187    3516.346
5   5582.544    3138.680    3995.311
6   9877.752    7798.371    8505.287
7   5137.488    4109.556    3301.129
8   13038.200   8853.721    8525.272

DF2:

    Charging Capacity
    2010    2011    2012
1   7.989   4.752   5.801
2   11.349  22.092  10.967
3   6.968   6.803   9.760
4   5.191   7.294   9.199
5   0.201   -1.204  10.488
6   14.598  13.077  17.004
7   5.134   12.945  8.970
8   44.680  23.607  24.395

我试图通过以下方式连接这两个数据帧:

l1=[df1,df2]
pd.concat(l1)

但我得到以下输出。为什么我为df2数据帧获得NaN?有没有办法在pandas中正确加入具有多级索引的两个数据帧?

    Charging Capacity       Total_Consumption
    2010    2011    2012    2010        2011        2012
1   NaN     NaN     NaN     8544.357    5133.553    5279.884
2   NaN     NaN     NaN     8581.545    6091.454    4323.611
3   NaN     NaN     NaN     4479.319    2784.283    1948.262
4   NaN     NaN     NaN     5493.114    3633.187    3516.346
5   NaN     NaN     NaN     5582.544    3138.680    3995.311
6   NaN     NaN     NaN     9877.752    7798.371    8505.287
7   NaN     NaN     NaN     5137.488    4109.556    3301.129
8   NaN     NaN     NaN     13038.200   8853.721    8525.272

1 个答案:

答案 0 :(得分:1)

使用axis=1

pd.concat([df1, df], axis=1)

输出:

  Total_Consumption                     Charging Capacity                
               2010      2011      2012              2010    2011    2012
1          8544.357  5133.553  5279.884             7.989   4.752   5.801
2          8581.545  6091.454  4323.611            11.349  22.092  10.967
3          4479.319  2784.283  1948.262             6.968   6.803   9.760
4          5493.114  3633.187  3516.346             5.191   7.294   9.199
5          5582.544  3138.680  3995.311             0.201  -1.204  10.488
6          9877.752  7798.371  8505.287            14.598  13.077  17.004
7          5137.488  4109.556  3301.129             5.134  12.945   8.970
8         13038.200  8853.721  8525.272            44.680  23.607  24.395