Setting DataFrame values with enlargement

前端 未结 3 1797
囚心锁ツ
囚心锁ツ 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:29

    In addition to previous answer, after reindexing you can use

    result.fillna(df1, inplace=True)
    

    so based on Jianxun Li's code (extended with one more column) you can try this

    # your data
    # ===========================================================
    df1 = pd.DataFrame(np.ones(12).reshape(4,3), columns='A B C'.split(), index=pd.date_range('2015-07-09 12:00:00', periods=4, freq='H'))
    df2 = pd.DataFrame(np.ones(20).reshape(4,5)*2, columns='A B C D E'.split(), index=pd.date_range('2015-07-09 14:00:00', periods=4, freq='H'))
    
    # processing
    # =====================================================
    # reindex to populate NaN
    result = df2.reindex(np.union1d(df1.index, df2.index))
    # fill NaN from df1
    result.fillna(df1, inplace=True)
    
    Out[3]:             
                         A  B  C   D   E
    2015-07-09 12:00:00  1  1  1 NaN NaN
    2015-07-09 13:00:00  1  1  1 NaN NaN
    2015-07-09 14:00:00  2  2  2   2   2
    2015-07-09 15:00:00  2  2  2   2   2
    2015-07-09 16:00:00  2  2  2   2   2
    2015-07-09 17:00:00  2  2  2   2   2
    

提交回复
热议问题