1

I have got the pandas dataframe as this below:

Dataset

I would like to convert currency if it's other then PLN. To do that i wrote the code :

def convert_currency():
   lst = []
   for i in risk['AMOUNT']:
       if risk['CURRENCY'].item() == 'EUR':
           lst.append(i * eurpln['EURPLN'][0])
       elif risk['CURRENCY'].item() == 'USD':
           lst.append(i * usdpln['USDPLN'][0])
       elif risk['CURRENCY'].item() == 'CHF':
           lst.append(i * chfpln['CHFPLN'][0])
       elif risk['CURRENCY'].item() == 'GBP':
           lst.append(i * gbppln['GBPPLN'][0])
       else:
           lst.append(i)
   return lst

but just after i tried to run this function i got the value error:

----> 4 if risk['CURRENCY'].item() == 'EUR':

ValueError: can only convert an array of size 1 to a Python scalar

Could You please help me find the reason of this problem and also the resolution?

2 Answers2

1

Here no loops are necessary.

For performance use map by dictionary and then multiple by AMOUNT column:

d = {'EUR':eurpln['EURPLN'][0], 'USD': usdpln['USDPLN'][0],
     'CHF':chfpln['CHFPLN'][0], 'GBP': gbppln['GBPPLN'][0]}

risk['AMOUNT'] = risk['CURRENCY'].map(d).mul(risk['AMOUNT'], fill_value=1)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
0

If performance is not important or small DataFrame use iterrows for looping:

def convert_currency():
   lst = []
   for _, row in risk.iterrows():
       if row['CURRENCY'].item() == 'EUR':
           lst.append(i * eurpln['EURPLN'][0])
       elif row['CURRENCY'].item() == 'USD':
           lst.append(i * usdpln['USDPLN'][0])
       elif row['CURRENCY'].item() == 'CHF':
           lst.append(i * chfpln['CHFPLN'][0])
       elif row['CURRENCY'].item() == 'GBP':
           lst.append(i * gbppln['GBPPLN'][0])
       else:
           lst.append(i)
   return lst
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
U13-Forward
  • 69,221
  • 14
  • 89
  • 114