Home > front end >  creating a function to find a certain type of currency and transform it in pandas
creating a function to find a certain type of currency and transform it in pandas

Time:05-20

I have been scraching my head with this issue for a while.. i'm a beginner both in python and pandas and i do not know if this is the best way to solve this issue.

I have a DF with the structure below

enter image description here

The values for currency can be USD , ARS or NaN.

I'm trying to write a function to transform those ARS value to USD with a set exchange value as it's an approximation.

So far i have wrote something like this .

def changeValue(df_price):
    if df_price["currency"] == "ARS" :
        for i in df_price["price"]:
            df_price["price"][i]= df_price["price"][i]/200
    return df_price

For some reason i'm getting this error.

KeyError: 'currency'

Edit. I forgot to add that df_price is the entire dataset, also, i'm creating this function to use apply over the dataframe, as in the next line of code.

 training_converted = training_data.apply(changeValue,axis= 0)

What is my function lacking in order to work with the dataframe . Also, maybe there is a better way of solving this issue using the built in pandas' methods and i'm not aware of it .

Thanks

CodePudding user response:

Here's how you work with apply. The function gets one row at a time, and you return a value for that row.

def changeValue(row):
    if row["currency"] == "ARS" :
        return row["price"]/200
    else
        return row['price']

...

training_converted = training_data.apply(changeValue,axis = 1)
  • Related