Create new column based on values ​​from other columns in python pandas

I have a pandas framework with one column showing currency and the other showing prices. I want to create a new column that standardizes USD prices based on values ​​from the other two columns.

eg.

  currency   price
  SGD        100
  USD        80
  EUR        75

      

the new column will have conditions similar to

if currency == SGD: price = price /1.37 etc.

so in the end it will look like

  currency   price   new_price
  SGD        100     72.99
  USD        80      80
  EUR        75      65.22

      

+3


source to share


1 answer


You can create a dictionary containing all currency conversions and then split the price column by the currency column matched in the dictionary.

df = pd.DataFrame({'currency': ['SGD', 'USD', 'EUR'], 
                   'price': [100, 80, 75]})
to_usd = {'USD': 1.0, 'SGD': 1.37, 'EUR': 1.15}
df['new_price'] = df.price / df.currency.map(to_usd)
print(df)

      



Printing

  currency  price  new_price
0      SGD    100  72.992701
1      USD     80  80.000000
2      EUR     75  65.217391

      

+3


source







All Articles