Pandas将日期增加1

2024-10-01 04:51:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个数据帧

ID    DateCol
1      26/06/2017
2      Employee Not Found

我想把日期增加1

预期输出为

ID    DateCol
1      27/06/2017
2      Employee Not Found

我试过了

temp_result_df['NewDateCol'] = pd.to_datetime(temp_result_df['DateCol']).apply(pd.DateOffset(1))

它不起作用,因为我相信上面有一根绳子


Tags: to数据iddfdatetimeemployeenotresult
1条回答
网友
1楼 · 发布于 2024-10-01 04:51:01

对于缺少的值,最好使用带有NaT的列中的datetimes-使用带有TimedeltaDay偏移量的^{}

temp_result_df['NewDateCol'] = pd.to_datetime(temp_result_df['DateCol'], errors='coerce') 

temp_result_df['NewDateCol'] += pd.Timedelta(1, 'd')
#alternative
#temp_result_df['NewDateCol'] += pd.offsets.Day(1)
print (temp_result_df)
   ID             DateCol NewDateCol
0   1          26/06/2017 2017-06-27
1   2  Employee Not Found        NaT

如果需要原始数据这样的字符串,则需要^{}replace

s = pd.to_datetime(temp_result_df['DateCol'], errors='coerce') + pd.Timedelta(1, 'd')

temp_result_df['NewDateCol'] = s.dt.strftime('%d/%m/%Y').replace('NaT','Employee Not Found')
print (temp_result_df)
   ID             DateCol          NewDateCol
0   1          26/06/2017          27/06/2017
1   2  Employee Not Found  Employee Not Found

相关问题 更多 >