[英]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 ![]() |
1 ![]() |
2 ![]() |
3 ![]() |
---|---|---|---|
yy![]() |
123 ![]() |
x ![]() |
|
xx ![]() |
445 ![]() |
r ![]() |
|
za![]() |
336 ![]() |
f ![]() |
|
gs ![]() |
775 ![]() |
e ![]() |
|
fr ![]() |
447 ![]() |
w ![]() |
df2: df2:
0 ![]() |
1 ![]() |
2 ![]() |
3 ![]() |
---|---|---|---|
T![]() |
0 ![]() |
x ![]() |
336 ![]() |
S![]() |
4 ![]() |
r ![]() |
447 ![]() |
R ![]() |
3 ![]() |
f ![]() |
445 ![]() |
Expected result should be:预期结果应该是:
df1: 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
:将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.