Home > Enterprise >  python change the price in various currency row in pandas, dataframe
python change the price in various currency row in pandas, dataframe

Time:09-23

this is my dataframe

id price  product
1  USD 4  shirt
2  EUR 7  pant
3  GBP 9  soxs
4  Yen 4  hat

and I want to convert the price row all to USD

this is the conversion table

1 EUR = 1.22 USD

1 GBP = 1.42 USD

1 Yen = 0.01 USD

I am a beginner and I hope you can help me, thanks.

CodePudding user response:

Create dictioanry for converting table first with USD for 1, then replace column by dictionary by Series.replace and multiple it by extracted numeric values by Series.str.extract:

d = {'EUR': 1.22, 'GBP':1.42, 'Yen':0.01, 'USD':1}

s1 = df['price'].replace(d, regex=True)
s2 = df['price'].str.extract('(\d \.?\d*)', expand=False).astype(float)
df['new price'] = s1 * s2
print (df)
   id  price product  new price
0   1  USD 4   shirt       4.00
1   2  EUR 7    pant       8.54
2   3  GBP 9    soxs      12.78
3   4  Yen 4     hat       0.04
  • Related