简体   繁体   English

比较两个不同的数据框并向列添加新值

[英]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].我有 2 个 DataFrame,其中 df1 的列必须与 df2 中具有不同维度的另一列进行比较,如果为真,则修改 de df1[3]。

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

df1: df1:

0 0 1 1 2 2 3 3
yy年年 123 123 x X
xx xx 445 445 r r
za 336 336 f F
gs GS 775 775 e e
fr FR 447 447 w w

df2: df2:

0 0 1 1 2 2 3 3
T 0 0 x X 336 336
S小号 4 4 r r 447 447
R R 3 3 f F 445 445

Expected result should be:预期结果应该是:

df1: df1:

0 0 1 1 2 2 3 3
yy年年 123 123 x X
xx xx 445 445 r r 4 4
za 336 336 f F 4 4
gs GS 775 775 e e
fr FR 447 447 w w 4 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 :boolean 索引isin一起使用:

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

output: 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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