pandas left join and update existing column

前端 未结 5 1636
忘掉有多难
忘掉有多难 2020-12-01 16:16

I am new to pandas and can\'t seem to get this to work with merge function:

>>> left       >>> right
   a  b   c       a  c   d 
0  1  4            


        
5条回答
  •  无人及你
    2020-12-01 16:29

    Here's a way to do it with join:

    In [632]: t = left.set_index('a').join(right.set_index('a'), rsuffix='_right')
    
    In [633]: t
    Out[633]: 
       b   c  c_right   d
    a                    
    1  4   9        7  13
    2  5  10        8  14
    3  6  11        9  15
    4  7  12      NaN NaN
    

    Now, we want to set null values of c_right (which is from the right dataframe) with values from c column from the left dataframe. Updated the below process with a method taking from @John Galt's answer

    In [657]: t['c_right'] = t['c_right'].fillna(t['c'])
    
    In [658]: t
    Out[658]: 
       b   c  c_right   d
    a                    
    1  4   9        7  13
    2  5  10        8  14
    3  6  11        9  15
    4  7  12       12 NaN
    
    In [659]: t.drop('c_right', axis=1)
    Out[659]: 
       b   c   d
    a           
    1  4   9  13
    2  5  10  14
    3  6  11  15
    4  7  12 NaN
    

提交回复
热议问题