Trying to convert currency in a df
using python.
I have two columns: price and currency.
I tried to use if/elif/else
statements but I'm doing something wrong.
Sample of df:
|price|currency|boat type| year built|
|-----|--------|---------|-----------|
|3490 |EUR |console | 2020 |
|2299 |EUR |fishing | 2019 |
|3500 |CHF |fishing | 1987 |
|4600 |£ |runabout | 2020 |
Any suggestions are appreciated. Thank you
Code I've tried...
if drop_boats['Currency'] == 'EUR':
drop_boats['Price'] = drop_boats['Price'] * 1.10
elif drop_boats['Currency'] == 'CHF':
drop_boats['Price'] = drop_boats['Price'] * 1.08
elif drop_boats['Currency'] == 'DKK':
drop_boats['Price'] = drop_boats['Price'] * 0.15
elif drop_boats['Currency'] == '£':
drop_boats['Price'] = drop_boats['Price'] * 1.32
else:
drop_boats['Price' ]= drop_boats['Price']
I'm getting this error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
.
CodePudding user response:
You can iter over the pandas rows using iter.rows()
and carry the calculation. Refer the below code:
for index, row in df.iterrows():
if row['Currency'] == 'EUR':
row['Price'] = row['Price'] * 1.10
elif row['Currency'] == 'CHF':
row['Price'] = row['Price'] * 1.08
elif row['Currency'] == 'DKK':
row['Price'] = row['Price'] * 0.15
elif row['Currency'] == '£':
row['Price'] = row['Price'] * 1.32
else:
row['Price' ]= row['Price']
CodePudding user response:
You probably want loc
with boolean indexing. If not show sample input and output data, please.
drop_boats.loc[drop_boats['Currency'].eq('EUR'), 'Price'] *= 1.10
CodePudding user response:
One way to accomplish what you want is like this:
for index, row in drop_boats.iterrows():
if row['Currency'] == 'EUR':
drop_boats.loc[index, 'Price'] = row['Price'] * 1.10
You can add your other conditions accordingly...