【问题标题】:Convert column with strings and missings to DateTime将包含字符串和缺失的列转换为 DateTime
【发布时间】:2019-11-30 14:34:31
【问题描述】:

我有一个数据框,其中包含字符串格式的多个日期(dtype:object)。但是,有时会丢失条目 (NaN) 或它们不包含带日期的字符串。这是一个例子:

data = [{"date_string" : "01:01:2019 00:00:00"}, {"date_string" : " "}, {"date_string" : np.NaN}]
df = pd.DataFrame(data)

将字符串转换为 DateTime 会引发错误:

df.date_string = df.date_string.apply(pd.to_datetime)


ValueError: String does not contain a date.

有没有办法绕过缺少日期的条目?

【问题讨论】:

  • 使用df.date_string.apply(pd.to_datetime,errors='coerce')
  • 工作了一个魅力!如果您愿意,请将其作为答案发布,我会将其标记为已完成 :) 谢谢!

标签: python-3.x pandas datetime error-handling


【解决方案1】:

pd.to_datetime 的文档说:

errors : {‘ignore’, ‘raise’, ‘coerce’}, default ‘raise’
If ‘raise’, then invalid parsing will raise an exception
If ‘coerce’, then invalid parsing will be set as NaT
If ‘ignore’, then invalid parsing will return the input

所以你应该通过errors='coerce' 绕过无效的日期时间值:

df.date_string.apply(pd.to_datetime,errors='coerce')

或者不申请单列:

pd.to_datetime(df.date_string,errors='coerce')

0   2019-07-22
1          NaT
2          NaT
Name: date_string, dtype: datetime64[ns]

【讨论】:

  • 谢谢!很好的答案!
  • @Rachel 没问题,我只是担心它是骗子,因此发表了评论。但找不到任何。干杯..!!
  • 我的荣幸。我也检查了骗子。在任何情况下都觉得有点愚蠢。新手错误...没有更仔细地阅读文档。谢谢!
猜你喜欢
  • 1970-01-01
  • 2023-02-01
  • 2023-03-13
  • 1970-01-01
  • 2021-03-31
  • 2022-10-23
  • 2012-02-02
  • 2011-10-16
  • 2016-03-17
相关资源
最近更新 更多