Replace data from one pandas dataframe to another

后端 未结 2 510
耶瑟儿~
耶瑟儿~ 2021-01-05 23:36

I have two dataframes df1 and df2 . They both contain time-series data, so it is possible some of the dates in df1 and df2 intersect with each other and the rest don\'t. My

相关标签:
2条回答
  • 2021-01-05 23:44

    update will align on the indices of both DataFrames:

    df1.update(df2)
    
    df1:
        A   B   C   D
    0   A0  BO  C0  D0
    1   A1  B1  C1  D1
    2   A2  B2  C2  D2
    3   A3  B3  C3  D3
    
    df2:
        A   B   C   D
    1   A4  B4  C4  D4
    2   A5  B5  C5  D5
    3   A6  B6  C6  D6
    4   A7  B7  C7  D7
    
    >>> df1.update(df2)
        A   B   C   D
    0  A0  BO  C0  D0
    1  A4  B4  C4  D4
    2  A5  B5  C5  D5
    3  A6  B6  C6  D6
    

    You then need to add the values in df2 not present in df1:

    >>> df1.append(df2.loc[[i for i in df2.index if i not in df1.index], :])
    Out[46]: 
        A   B   C   D
    0  A0  BO  C0  D0
    1  A4  B4  C4  D4
    2  A5  B5  C5  D5
    3  A6  B6  C6  D6
    4  A7  B7  C7  D7
    
    0 讨论(0)
  • 2021-01-06 00:04

    I just saw this question and realized it is almost identical to one that I just asked today and that @Alexander (the poster of the answer above) answered very nicely:

    pd.concat([df1[~df1.index.isin(df2.index)], df2])
    

    See pandas DataFrame concat / update ("upsert")? for the discussion.

    0 讨论(0)
提交回复
热议问题