【问题标题】:why does pd.to_datetime fail to convert?为什么 pd.to_datetime 无法转换?
【发布时间】:2017-12-03 00:41:53
【问题描述】:

我有一个包含日期值的对象列。从 csv 读取后,我手动放置了 2016-08-31 而不是 NaN。

            close_date
0  1948-06-01 00:00:00   
1  2016-08-31 00:00:00   
2  2016-08-31 00:00:00   
3  1947-07-01 00:00:00   
4  1967-05-31 00:00:00

运行df['close_date'] = pd.to_datetime(df['close_date']) 导致

TypeError: invalid string coercion to datetime

添加coerce=Trueargument 会导致:

TypeError: to_datetime() got an unexpected keyword argument 'coerce'

此外,即使我将列称为“close_date”,数据框中的所有列,一些 int64、float64 和 datetime64[ns],都会更改为 dtype 对象。

我做错了什么?

【问题讨论】:

    标签: python-2.7 pandas python-datetime


    【解决方案1】:

    您需要 errors='coerce' 参数将一些不可解析的值转换为 NaT:

    df['close_date'] = pd.to_datetime(df['close_date'], errors='coerce')
    print (df)
      close_date
    0 1948-06-01
    1 2016-08-31
    2 2016-08-31
    3 1947-07-01
    4 1967-05-31
    
    print (df['close_date'].dtypes)
    datetime64[ns]
    

    但如果有一些混合值 - 带有日期时间的数字首先转换为 str

    df['close_date'] = pd.to_datetime(df['close_date'].astype(str), errors='coerce')
    

    【讨论】:

      猜你喜欢
      • 2014-12-24
      • 2021-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-14
      • 1970-01-01
      • 2011-12-20
      • 2011-06-29
      相关资源
      最近更新 更多