how to update existing data frame in pandas?

前端 未结 1 2059
孤独总比滥情好
孤独总比滥情好 2021-01-19 03:34

Given these two data frames:

>>> df1 = pd.DataFrame({\'c1\':[\'a\',\'a\',\'b\',\'b\'], \'c2\':[\'x\',\'y\',\'x\',\'y\'], \'val\':0})
>>> df         


        
1条回答
  •  醉话见心
    2021-01-19 03:55

    Yes, take a look at combine_first or update. For example:

    >>> df1['val'] = df2['val'].combine_first(df1['val'])
    >>> df1
    Out[26]:
        c1  c2  val
    0    a   x   12
    1    a   y   31
    2    b   x   14
    3    b   y   0
    

    EDIT: to combine according to c1 and c2 ignoring the current index:

    >>> df1['val'] = df2.set_index(['c1','c2'])['val'].combine_first(df1.set_index(['c1','c2'])['val']).values
    >> df1
    Out[25]:
        c1  c2  val
    0    a   x   12
    1    a   y   31
    2    b   x   0
    3    b   y   14
    

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