i am trying to convert each value (USD100-120 e.g.) in a column of my dataset to USD (there are many different currencys like EUR etc.) So based on their Currency i need to convert them with the respective conversion rate. My input file is something like this:
d = {'location': ['US', 'UK'], 'price': ['USD10-20', 'GBP10-20']}
df = pd.DataFrame(data=d)
location|price
US |USD10-20
UK |GBP10-20
etc.
I tried this :
def convertCurrency(price):
c=CurrencyConverter()
currency= price[0:3]
numbers=re.findall(r'\d+',price)
lowerbound= re.findall(r'\d+',price)[0]
res=""
upperbound='x'
if currency=='USD':
return price
if len(numbers)>1:
upperbound=numbers[1]
first=int(c.convert(int(lowerbound),price,"USD"))
if upperbound != 'x':
second=int(c.convert(int(upperbound),price,"USD"))
res=''+currency+str(first)+"-"+str(second)
else:
res = '' + currency + str(first)
return res
and calling it with apply
df['price'] = df.apply(lambda row: convertCurrency(row.price), axis=1)
but this takes way too long. i also tried this:
df['price'] = convertCurrency(df['price'])
but this will throw an error because the function gets a series object and not a string. What do i have to change or Is there another way? My desired result will be
location|price
US |USD10-20
UK |USD14-28