简体   繁体   中英

Selectively replace values in dataframe from another dataframe

I have two dataframes:

df1

   Company Name     Symbol     ID
0       AAA Inc  No Symbol    123
1       BBB Inc          B    456
2       CCC Inc          C    789
3       DDD Inc          D    112
4       EEE Inc          E    134
5       FFF Inc  No Symbol    156

df2

   Company Name     Symbol     ID
0       Aaa Inc          A    123
1       bbb Inc          B    456
2         C  Co  No Symbol    789
3       fff Inc          F    156
4       ZZZ Inc          Z    999

And I want to replace only the No Symbol values in df1 with the Symbol from df2 by using ID as the lookup, so that the output would look like this:

   Company Name     Symbol     ID
0       AAA Inc          A    123
1       BBB Inc          B    456
2       CCC Inc          C    789
3       DDD Inc          D    112
4       EEE Inc          E    134
5       FFF Inc          F    156

How do I achieve this?

df1_no_symbol_id = df1[df1['Symbol']=='No Symbol']['ID']

df2_symbol_id_values_list = df2[df2['ID'].isin(df1_no_symbol_id)].to_dict('records')

for i in df2_symbol_id_values_list:
    id = i['ID']
    value = i['Symbol']
    df1.loc[df1.ID==id, 'Symbol'] = value

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