Setting DataFrame values with enlargement

前端 未结 3 1795
囚心锁ツ
囚心锁ツ 2020-12-20 16:46

I have two DataFrames (with DatetimeIndex) and want to update the first frame (the older one) with data from the second frame (the newer one).

3条回答
  •  借酒劲吻你
    2020-12-20 17:47

    df2.combine_first(df1) (documentation) seems to serve your requirement; PFB code snippet & output

    import pandas as pd
    
    print 'pandas-version: ', pd.__version__
    
    df1 = pd.DataFrame.from_records([('2015-07-09 12:00:00',1,1,1),
                                     ('2015-07-09 13:00:00',1,1,1),
                                     ('2015-07-09 14:00:00',1,1,1),
                                     ('2015-07-09 15:00:00',1,1,1)],
                                    columns=['Dt', 'A', 'B', 'C']).set_index('Dt')
    # print df1
    
    df2 = pd.DataFrame.from_records([('2015-07-09 14:00:00',2,2,2,2),
                                     ('2015-07-09 15:00:00',2,2,2,2),
                                     ('2015-07-09 16:00:00',2,2,2,2),
                                     ('2015-07-09 17:00:00',2,2,2,2),],
                                   columns=['Dt', 'A', 'B', 'C', 'D']).set_index('Dt')
    res_combine1st = df2.combine_first(df1)
    print res_combine1st
    

    output

    pandas-version:  0.15.2
                         A  B  C   D
    Dt                              
    2015-07-09 12:00:00  1  1  1 NaN
    2015-07-09 13:00:00  1  1  1 NaN
    2015-07-09 14:00:00  2  2  2   2
    2015-07-09 15:00:00  2  2  2   2
    2015-07-09 16:00:00  2  2  2   2
    2015-07-09 17:00:00  2  2  2   2
    

提交回复
热议问题