我已经编写了一个代码来修改日期,以便在2/29/2008减少1天。 代码成功执行并向我显示输出但不更新数据帧。
TO
我写了下面的代码,它给了我输出但它没有更新数据帧
Name Maint Start Date
Yasin 02/29/08
Susy 01/04/15
James 04/14/06
然后我将其修改为,但所有没有闰年数据的字段都变为空白。
spend_sw[spend_sw['Maint Start Date'] == '02/29/2008'].apply(lambda x: pd.datetime(x['Maint Start Date'].year , x['Maint Start Date'].month, x['Maint Start Date'].day - 1), axis=1)
您能告诉我如何修改现有数据帧的值。
答案 0 :(得分:2)
我认为您可以先转换Maint Start Date
to_datetime
列中的所有值,然后使用ix
进行过滤,并在to_timedelta
创建的一天减去Timedelta
:< / p>
print (spend_sw)
Name Maint Start Date
0 Yasin 02/29/08
1 Susy 01/04/15
2 James 04/14/06
spend_sw['Maint Start Date'] = pd.to_datetime(spend_sw['Maint Start Date'])
print (spend_sw.ix[spend_sw['Maint Start Date'] == '02/29/08', 'Maint Start Date'])
0 2008-02-29
Name: Maint Start Date, dtype: datetime64[ns]
spend_sw.ix[spend_sw['Maint Start Date'] == '02/29/08', 'Maint Start Date'] = \
spend_sw.ix[spend_sw['Maint Start Date'] == '02/29/08', 'Maint Start Date'] -
pd.to_timedelta(1, unit='d')
print (spend_sw)
Name Maint Start Date
0 Yasin 2008-02-28
1 Susy 2015-01-04
2 James 2006-04-14
spend_sw['Maint Start Date'] = pd.to_datetime(spend_sw['Maint Start Date'])
date = pd.to_datetime('02/29/08')
date1 = date - pd.offsets.Day(1)
#mask by condition
ma = spend_sw['Maint Start Date'] == date
spend_sw['Maint Start Date'] = spend_sw['Maint Start Date'].mask(ma, date1)
print (spend_sw)
Name Maint Start Date
0 Yasin 2008-02-28
1 Susy 2015-01-04
2 James 2006-04-14