简体   繁体   中英

Compare two different dataframes and add new values to a column

I have 2 DataFrames, where a column of df1 must be compared to another column, in df2, that have different dimensions, and if true, modify de df1[3].

if df1.loc[df1[1]] == df2.loc[df2[3]]:  
    df1[3] = 4

df1:

0 1 2 3
yy 123 x
xx 445 r
za 336 f
gs 775 e
fr 447 w

df2:

0 1 2 3
T 0 x 336
S 4 r 447
R 3 f 445

Expected result should be:

df1:

0 1 2 3
yy 123 x
xx 445 r 4
za 336 f 4
gs 775 e
fr 447 w 4
 KeyError:None of [Index ... type='object', length=...)] are in the [index]"

Can someone help me with this? I know that probably is a simple thing, but i've tried a lot of ways and none of works.

Use boolean indexing with isin :

df1.loc[df1[1].isin(df2[3]), 3] = 4

output:

    0    1  2    3
0  yy  123  x  NaN
1  xx  445  r  4.0
2  za  336  f  4.0
3  gs  775  e  NaN
4  fr  447  w  4.0

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