i have a dataframe with this format :
Ihave created an empty column USD Amount and i want to fill it with the currnecy converted in USD. i used the below code :
for cur in df1['CurrencyCode']:
if cur=='RMB':
df1['USD Amount']=df1['Amount']/6.39
elif cur=='THB':
df1['USD Amount']=df1['Amount']/33.26
elif cur=='INR':
df1['USD Amount']=df1['Amount']/75.01
elif cur=='KRW':
df1['USD Amount']=df1['Amount']/1,171.56
elif cur=='VND':
df1['USD Amount']=df1['Amount']/22,759.00
elif cur=='IDR':
df1['USD Amount']=df1['Amount']/14,188.86
elif cur=='MYR':
df1['USD Amount']=df1['Amount']/4.15
elif cur=='USD':
df1['USD Amount']=df1['Amount']/1
elif cur=='EUR':
df1['USD Amount']=df1['Amount']/0.86
elif cur=='TUS':
df1['USD Amount']=df1['Amount']/1
elif cur=='GBP':
df1['USD Amount']=df1['Amount']/33.26
else:
df1['USD Amount']=df1['Amount']
but i get:
7 df1['USD Amount']=df1['Amount']/75.01
8 elif cur=='KRW':
----> 9 df1['USD Amount']=df1['Amount']/1,171.56
10 elif cur=='VND':
11 df1['USD Amount']=round(df1['Amount']/22,759.00,2)
ValueError: Length of values (2) does not match length of index (9892)
What am i doing wrong here?
CodePudding user response:
I think these are comma issues. I think in line 9 the value should be 1171.56 and in line 11 it should be 22759 and line 13 should be 14188.86.
CodePudding user response:
I removed the commas in the conversion rates and created a function to apply to the dataframe
dict=[{'Username':'GEO','CurrencyCode':'EUR','Amount':1000},
{'Username':'BUCK17','CurrencyCode':'GBP','Amount':1000},
{'Username':'DRAC77','CurrencyCode':'LBP','Amount':1000}]
df=pd.DataFrame(dict)
def ConvertCurrency(row):
ret_val=0.0
if row['CurrencyCode']=='RMB':
ret_val=row['Amount']/6.39
elif row['CurrencyCode']=='THB':
ret_val=row['Amount']/33.26
elif row['CurrencyCode']=='INR':
ret_val=row['Amount']/75.01
elif row['CurrencyCode']=='KRW':
ret_val=row['Amount']/1171.56
elif row['CurrencyCode']=='VND':
ret_val=row['Amount']/22759.00
elif row['CurrencyCode']=='IDR':
ret_val=row['Amount']/14188.86
elif row['CurrencyCode']=='MYR':
ret_val=row['Amount']/4.15
elif row['CurrencyCode']=='USD':
ret_val=row['Amount']/1
elif row['CurrencyCode']=='EUR':
ret_val=row['Amount']/0.86
elif row['CurrencyCode']=='TUS':
ret_val=row['Amount']/1
elif row['CurrencyCode']=='GBP':
ret_val=row['Amount']/33.26
else:
ret_val=row['Amount']
return ret_val
df['USD Amount']=df.apply(ConvertCurrency,axis=1)
print(df)
output:
Username CurrencyCode Amount USD Amount
0 GEO EUR 1000 1162.790698
1 BUCK17 GBP 1000 30.066146
2 DRAC77 LBP 1000 1000.000000