Pandas DataFrame currency conversion

做~自己de王妃 提交于 2021-02-08 08:17:07

问题


I have DataFrame with two columns:

col1     | col2

20         EUR
31         GBP
5          JPY

I may have 10000 rows like this

How to do fast currency conversion to base currency being GBP?

should I use easymoney? I know how to apply conversion to single row but I do not know how to iterate through all the rows fast.

EDIT: I would like to apply sth as:

def convert_currency(amount, currency_symbol):
    converted = ep.currency_converter(amount=1000, from_currency=currency_symbol, to_currency="GBP")
    return converted


df.loc[df.currency != 'GBP', 'col1'] = convert_currency(currency_data.col1, df.col2
                                                                                  )

but it does not work yet.


回答1:


Join a third column with the conversion rates for each currency, joining on the currency code in col2. Then create a column with the translated amount.

dfRate:
code | rate
EUR    1.123
USD    2.234

df2 = pd.merge(df1, dfRate, how='left', left_on=['col2'], right_on=['code'])

df2['translatedAmt'] = df2['col1'] / df2['rate']



回答2:


df = pd.DataFrame([[20, 'EUR'], [31, 'GBP'], [5, 'JPY']], columns=['value', 'currency'])
print df

   value currency
0     20      EUR
1     31      GBP
2      5      JPY

def convert_to_gbp(args):  # placeholder for your fancy conversion function
    amount, currency = args
    rates = {'EUR': 2, 'JPY': 10, 'GBP': 1}
    return rates[currency] * amount

df.assign(**{'In GBP': df.apply(convert_to_gbp, axis=1)})

   value currency  In GBP
0     20      EUR      40
1     31      GBP      31
2      5      JPY      50


来源:https://stackoverflow.com/questions/46227944/pandas-dataframe-currency-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!