[英]Compare two different dataframes and add new values to a column
我有 2 個 DataFrame,其中 df1 的列必須與 df2 中具有不同維度的另一列進行比較,如果為真,則修改 de df1[3]。
if df1.loc[df1[1]] == df2.loc[df2[3]]:
df1[3] = 4
df1:
0 | 1 | 2 | 3 |
---|---|---|---|
年年 | 123 | X | |
xx | 445 | r | |
扎 | 336 | F | |
GS | 775 | e | |
FR | 447 | w |
df2:
0 | 1 | 2 | 3 |
---|---|---|---|
噸 | 0 | X | 336 |
小號 | 4 | r | 447 |
R | 3 | F | 445 |
預期結果應該是:
df1:
0 | 1 | 2 | 3 |
---|---|---|---|
年年 | 123 | X | |
xx | 445 | r | 4 |
扎 | 336 | F | 4 |
GS | 775 | e | |
FR | 447 | w | 4 |
KeyError:None of [Index ... type='object', length=...)] are in the [index]"
有人可以幫我弄這個嗎? 我知道這可能是一件簡單的事情,但我嘗試了很多方法,但都沒有奏效。
將boolean 索引與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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.