Creating a pandas DataFrame from columns of other DataFrames with similar indexes

后端 未结 3 480
自闭症患者
自闭症患者 2020-12-28 12:02

I have 2 DataFrames df1 and df2 with the same column names [\'a\',\'b\',\'c\'] and indexed by dates. The date index can have similar values. I would like to create a DataFra

3条回答
  •  忘掉有多难
    2020-12-28 12:45

    You can use concat:

    In [11]: pd.concat([df1['c'], df2['c']], axis=1, keys=['df1', 'df2'])
    Out[11]: 
                     df1       df2
    2014-01-01       NaN -0.978535
    2014-01-02 -0.106510 -0.519239
    2014-01-03 -0.846100 -0.313153
    2014-01-04 -0.014253 -1.040702
    2014-01-05  0.315156 -0.329967
    2014-01-06 -0.510577 -0.940901
    2014-01-07       NaN -0.024608
    2014-01-08       NaN -1.791899
    
    [8 rows x 2 columns]
    

    The axis argument determines the way the DataFrames are stacked:

    df1 = pd.DataFrame([1, 2, 3])
    df2 = pd.DataFrame(['a', 'b', 'c'])
    
    pd.concat([df1, df2], axis=0)
       0
    0  1
    1  2
    2  3
    0  a
    1  b
    2  c
    
    pd.concat([df1, df2], axis=1)
    
       0  0
    0  1  a
    1  2  b
    2  3  c
    

提交回复
热议问题