Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

if / then statement for currency in python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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().

>Solution :

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading