【问题标题】:pd.to_datetime errors = 'ignore' strange behaviorpd.to_datetime 错误 = '忽略' 奇怪的行为
【发布时间】:2021-12-01 02:27:36
【问题描述】:

我有一个名为“result”的数据框,其中包含一个名为“Action”的列。此列包含许多字符串,其中一些是日期。我正在尝试将包含日期的字符串转换为日期时间,忽略不包含日期的行,因为它们会出错。

通常我会使用 pd.to_datetime(column =, format =, errors = 'ignore') 但在这种情况下,这不会转换任何内容。

但是,当我更改 errors = 'coerce' 时,它会转换日期,但当然会将其他所有内容转换为 NaN。我想使用忽略,因为其他行中仍有有价值的数据。

result["Action"] = pd.to_datetime(result["Action"], format = '%A %B %d %Y', errors = 'ignore')

result["Action"] = pd.to_datetime(result["Action"], format = '%A %B %d %Y', errors = 'coerce')

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    如果errors 设置为ignore,则invalid parsing will return the input。所以在你的情况下,输入是result["Action"](整列)。

    解决此问题的方法是将pd.to_datetimeerrors='ignore' 逐行应用。通过这样做,如果该行不遵循format,您将获得相同的行。

    >>> import pandas as pd
    >>>
    >>> df = pd.DataFrame({'Action': ['Tuesday November 30 2021', 'Appointment time clicked']})
    >>> df
                         Action
    0  Tuesday November 30 2021
    1  Appointment time clicked
    >>>
    >>> def custom(action):
    ...     date_time = pd.to_datetime(action, format='%A %B %d %Y', errors='ignore')
    ...     return date_time
    ...
    >>> df.Action = df.Action.apply(custom)
    >>> df
                         Action
    0       2021-11-30 00:00:00
    1  Appointment time clicked
    

    【讨论】:

    • 根据文档,无效解析仅指非指定格式的数据:如果为“raise”,则无效解析将引发异常。如果“强制”,则无效解析将被设置为 NaT。如果“忽略”,则无效解析将返回输入也就是说,您的解决方案有效!奇怪的是,我必须使用 .apply 来处理被忽略的错误,而不是强制错误。
    【解决方案2】:

    我能想到的一种解决方法是在需要时重新解析 DF

    for d in result['Action']:
      try:
        res = pd.to_datetime(d, format = '%A %B %d %Y')
        print(res)
      except:
        res = pd.to_datetime(d, format = '%A %B %d %Y', errors='ignore')
        print(res)
    

    【讨论】:

      【解决方案3】:

      您可以执行以下操作:

      tmp = pd.to_datetime(result["Action"], format='%A %B %d %Y', errors='coerce')
      result.Action = result.Action.where(tmp.isna(), tmp.dt.date)
      

      结果

      result = 
                            Action
      0   Tuesday November 30 2021
      1  Appointment time clicked:
      2  Appointment date clicked:
      3   Tuesday November 30 2021
      4  Appointment time clicked:
      5   Tuesday November 30 2021
      6   Tuesday November 30 2021
      

                            Action
      0                 2021-11-30
      1  Appointment time clicked:
      2  Appointment date clicked:
      3                 2021-11-30
      4  Appointment time clicked:
      5                 2021-11-30
      6                 2021-11-30
      

      【讨论】:

        猜你喜欢
        • 2012-07-17
        • 2023-04-09
        • 1970-01-01
        • 2012-11-26
        • 2015-07-27
        • 2015-08-11
        • 2015-12-05
        • 2020-09-02
        • 2012-12-27
        相关资源
        最近更新 更多