简体   繁体   中英

fill column values based on row values from another dataframe using pandas

I basically have this

   first    
0   bar 
1   bar 
2   foo 
3   foo 
   bar foo
0   a   b

I want to insert value in dataframe 2 to dataframe 1, so the final result should be something like this

   first    
0   a   
1   a   
2   b   
3   b   

You can simply use replace like so:

>>> df1.replace(df2.transpose()[0])
    first
0     a
1     a
2     b
3     b

If you want to check efficiency:

%timeit df1.replace(df2.transpose()[0])
711 µs ± 18.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

You can use join on a transposed df2:

df1.set_index('first').join(df2.T)

Out[11]:
     0
bar  a
bar  a
foo  b
foo  b

Or with a dictionary:

df1['first'].map(df2.T.to_dict()[0])

Out[17]: 
0    a
1    a
2    b
3    b
Name: first, dtype: object

Or with merge:

df1.merge(df2.T.reset_index(), left_on=['first'], right_on=['index'])

  first index  0
0   bar   bar  a
1   bar   bar  a
2   foo   foo  b
3   foo   foo  b

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM