[英]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.