我在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)
但是,在运行代码后,变量taa
不会更改其值。
我想知道原因,以及如何修改代码以获得taa. accMonth=[‘200703’, ‘200703’, ‘200703’, ‘200703’, ‘200703’]
根据Nickil Maveli和Simon的建议,以下修改后的代码可以很好地运作。
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)
答案 0 :(得分:1)
与所有pandas函数一样,它们不会更改数据框但返回已更改的df。
所以你需要taa = taa.apply ....
或者您可以设置inplace = true