[英]Pandas - replace values of a column if other values from same row appear in second data frame
输入是两个数据框。 下面是它们的简短版本,仅有几行。
df1
+-----+------+------+
| No | Type | Desc |
+-----+------+------+
| 123 | A | Bla |
| 123 | B | Bla |
| 123 | D | Bla |
| 342 | A | Bla |
| 342 | C | Bla |
| 543 | B | Bla |
| 543 | C | Bla |
+-----+------+------+
df2
+-----+------+------+
| No | Type | Desc |
+-----+------+------+
| 123 | A | Lala |
| 342 | A | Lala |
| 342 | C | Lala |
+-----+------+------+
这两个数据框都比上面的列多,但是在这种情况下其他两个都没有关系。
我想为df1
行更改Desc
to Done
列的值,以防该行(表示No
和Type
)也出现在df2
。
df1
+-----+------+------+
| No | Type | Desc |
+-----+------+------+
| 123 | A | Done |
| 123 | B | Bla |
| 123 | D | Bla |
| 342 | A | Done |
| 342 | C | Done |
| 543 | B | Bla |
| 543 | C | Bla |
+-----+------+------+
谢谢 :)
使用与numpy.where
merge
:
df3 = df1[['No','Type']].merge(df2, on=['No','Type'], how='left')
df3['Desc'] = np.where(df3['Desc'].notnull(), 'Done', df1['Desc'])
print (df3)
No Type Desc
0 123 A Done
1 123 B Bla
2 123 D Bla
3 342 A Done
4 342 C Done
5 543 B Bla
6 543 C Bla
您可以通过左合并找到df2
中存在的df1
行,然后将Desc
更改为Done
。
mer = df1.merge(df2, on=['No', 'Type'], how='left')
mer.loc[mer['Desc_y'].notnull(), 'Desc_x'] = 'Done'
df1['Desc'] = mer['Desc_x']
输出:
No Type Desc
0 123 A Done
1 123 B Bla
2 123 D Bla
3 342 A Done
4 342 C Done
5 543 B Bla
6 543 C Bla
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.