简体   繁体   中英

Pandas - replace values of a column if other values from same row appear in second data frame

Input are two dataframes. Below are short versions of them with only a few rows.

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 |
+-----+------+------+

Both data frames have more than the columns above, but the others do not matter in this case.

I would like to change values of column Desc to Done for rows of df1 in case this row (meaning No and Type ) also appear in 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  |
+-----+------+------+

Thank you :)

Use merge with numpy.where :

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

You can find the rows of df1 , that are present in df2 with a left merge and then change the Desc to Done .

mer = df1.merge(df2, on=['No', 'Type'], how='left')
mer.loc[mer['Desc_y'].notnull(), 'Desc_x'] = 'Done'
df1['Desc'] = mer['Desc_x']

Output:

    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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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