inaMinute
inaMinute

Reputation: 585

why can’t the function DataFrame.apply change the DataFrame values

I have an example run in spyder.

taa=pd.DataFrame({'month':[4,4,4,4,4],
                          'year':[2007,2007,2007,2007,2007],
                          'accMonth':[np.nan,np.nan,np.nan,np.nan,np.nan]})
def df_ret_tempFun(row):
    if row['month']<=3:
        row['accMonth']=str(row['year']-1)+'12'
    elif row['month']<=6 and row['month']>3:
        row['accMonth']=str(row['year'])+'03'
    elif row['month']<=9 and row['month']>6:
        row['accMonth']=str(row['year'])+'06'
    else:
         row['accMonth']=str(row['year'])+'09'

taa.apply(df_ret_tempFun,axis=1)

however ,the variable taa does not change its values after I run the code. I want to know why,and how to modify code to get a result like taa. accMonth=[‘200703’, ‘200703’, ‘200703’, ‘200703’, ‘200703’]

According to Nickil Maveli and Simon's suggestion ,the following modified code can work well.

taa=pd.DataFrame({'month':[4,4,4,4,4],
                          'year':[2007,2007,2007,2007,2007],
                          'accMonth':[np.nan,np.nan,np.nan,np.nan,np.nan]})
def df_ret_tempFun(row):
    if row['month']<=3:
        row['accMonth']=str(row['year']-1)+'12'
    elif row['month']<=6 and row['month']>3:
        row['accMonth']=str(row['year'])+'03'
    elif row['month']<=9 and row['month']>6:
        row['accMonth']=str(row['year'])+'06'
    else:
         row['accMonth']=str(row['year'])+'09'
    return row

taa=taa.apply(df_ret_tempFun,axis=1)

Upvotes: 0

Views: 242

Answers (1)

simon
simon

Reputation: 2811

As with all pandas functions they do not change the data frame but return the changed df.

So you need taa = taa.apply....

Or you can set inplace=true

Upvotes: 1

Related Questions