greycat90
greycat90

Reputation: 55

List comprehension currency conversion pass statement

I am trying to write list comprehension to convert currencies in a pandas dataframe to all usd. I am using the forex_python.converter to get the exchange rates.

the data looks like:

Amount Currency Amount_USD
20 usd
45 cad
17 gbp

I want to write a loop to apply the exchange rate of a particular day to convert each row to usd, but if the row is usd then Amount_USD should just equal Amount

So far I have tried:

for currency in currencies:
    if currency == 'usd':
        data['Amount_USD'] == data['Amount']
    else:
        date_obj=datetime.datetime(2020,8,1)
        currency2 = print('"{0}"'.format(currency))
        rate = c.get_rate(currency2,'USD', date_obj)
        data['Amount_USD'] = np.where(data['Currency']== currency2, data['Amount']*rate , np.nan)

But currently the code is applying an exchange rate to USD values.

Upvotes: 0

Views: 86

Answers (1)

Poe Dator
Poe Dator

Reputation: 4913

I suggest this rewrite:

for currency in currencies:
    if currency != 'usd':
        date_obj=datetime.datetime(2020,8,1)
        currency2 = print('"{0}"'.format(currency))
        rate = c.get_rate(currency2,'USD', date_obj)
    else:
        rate = 1
    data.loc[data.currency == currency, 'Amount_USD'] = data['Amount'] * rate

Upvotes: 1

Related Questions