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 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.