swissmade
swissmade

Reputation: 87

pandas replace values based on values from another column

I have two dataframe (data and priceMapping)

Data:

       Global id   Price
0   AR.1852218.1     
1   AR.1852223.1     0,6
2   AR.1852251.1    0,56
3   AR.1852254.1    
4   AR.1852257.1    0,25
5   AR.1852386.1    0,33
6   AR.1852549.1    

priceMapping:

        G.ID       Price
0   AR.1852218.1     0,1
1   AR.1852254.1    0,25
2   AR.1852549.1    0,33

I would like to fill the price that is in the priceMapping dataframe based on the criteria Global id=G.ID.

Thanks in advance for your help.

Laurent

Upvotes: 2

Views: 53

Answers (1)

jezrael
jezrael

Reputation: 862481

Use Series.map by Series created by priceMapping and then replace not matched values to original by Series.fillna, because not matched values create missing values:

s = priceMapping.set_index('G.ID')['Price']
Data['Price'] = Data['Global id'].map(s).fillna(Data['Price'])
print (Data)
      Global id Price
0  AR.1852218.1   0,1
1  AR.1852223.1   0,6
2  AR.1852251.1  0,56
3  AR.1852254.1  0,25
4  AR.1852257.1  0,25
5  AR.1852386.1  0,33
6  AR.1852549.1  0,33

Another idea is use Series.replace:

s = priceMapping.set_index('G.ID')['Price']
Data['Price'] = Data['Global id'].replace(s)

Upvotes: 2

Related Questions