Search code examples
pythonpandasdataframenumpyseries

Python scalar value error during for loop


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?


Solution

  • 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)