Angéliquecln
Angéliquecln

Reputation: 21

Create a column based on the values of another dataframe

I have this first dataframe df :

                       cur_cost_id   cur_sales_id  product_description
date_facture                                                      
2020-01-01 00:20:09            2             1                  io
2020-01-01 00:25:12            2             2                  io
2020-01-01 00:25:35            2             1                  io
2020-01-01 00:25:50            2             4                  io
2020-01-01 00:25:52            2             2                  io

Using another dataframe below on exchange rates I created the avg average:

avg=df.mean(axis=1)

2020-05-27  2020-04-23  2020-06-12  2020-03-31  2020-03-30  2020-06-19  \
AUD    1.507142    1.570553    1.454972    1.639923    1.633225    1.450580   
BGN    1.779456    1.815633    1.730184    1.785141    1.772521    1.744692   
EUR    5.338823    5.446157    5.076787    5.202720    5.121533    5.354951   

I try to add a column to the first dataframe so that if cur_sales_id=1 then the value in the new column is avg['EUR'].

I tried this :

def taux_change(row):
   if row['cur_sales_id'] == 1:
       val = avg['EUR']
   return val

df['Taux_change'] = df.apply(taux_change, axis=1)

But I have this error :

("local variable 'val' referenced before assignment", 'occurred at index 2020-01-01 00:20:09')

Somebody could explain me why please ?

Upvotes: 0

Views: 33

Answers (2)

Fred
Fred

Reputation: 502

In your function do you not assign a value for val if row['cur_sales_id'] != 1.

A better way to write your function would be

def taux_change(row):
    if row['cur_sales_id'] == 1:
        val = avg['EUR']
    else:
        val = None
    return val

df['Taux_change'] = df.apply(taux_change, axis=1)

An alternate way would be:

df.loc[df['cur_sales_id'] == 1,'Taux_change'] = avg['EUR']

And even better might be using the map function and create a dictionary of the average exchange rates avg_xr_dict and then:

df["Taux_change"] = df["cur_sales_id"].map(avg_xr_dict)

Upvotes: 1

Subbu VidyaSekar
Subbu VidyaSekar

Reputation: 2615

def taux_change(row):
   if row['cur_sales_id'] == 1:
       val = avg['EUR']
   return val

df['Taux_change'] = df.apply(taux_change, axis=1)

you should give a tab to the line return val because it returns the val from the function. other wise it would be like a normal code flow.

Upvotes: 1

Related Questions