当列中有空格时,将dataframe列设置为键入datetime

2024-05-29 10:02:43 发布

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

我有一个dataframe(df),其中有两列的head看起来像

    name                start                  end   
0   John  2018-11-09 00:00:00  2012-03-01 00:00:00
1  Steve  1990-09-03 00:00:00  
2   Debs  1977-09-07 00:00:00  2012-07-02 00:00:00
3  Mandy                       2009-01-09 00:00:00
4  Colin  1993-08-22 00:00:00  2002-06-03 00:00:00

startend列的类型为object。我想将类型更改为datetime,以便可以使用以下内容:

referenceError = DeptTemplate['start'] > DeptTemplate['end']

我正在尝试使用以下命令更改类型:

df['start'].dt.strftime('%d/%m/%Y') 
df['end'].dt.strftime('%d/%m/%Y') 

但我认为,如果有一些行的列中没有日期,这就产生了问题。有人能告诉我我如何设置任何空白值,以便我可以改变日期时间类型和运行我的分析请

谢谢


Tags: name类型dataframedfdtjohnstarthead
1条回答
网友
1楼 · 发布于 2024-05-29 10:02:43

.to_datetimedocs中所示,您可以使用errorskwarg设置行为。您还可以使用formatkwarg设置strftime格式

# Bad values will be NaT
df["start"] = pd.to_datetime(df.start, errors='coerce', format='%d/%m/%Y')

如注释中所述,如果必须使用strftime,可以使用replace来准备列

相关问题 更多 >

    热门问题