Pandas.to_datetime函数无提示失败

 冬天的芦苇2011 发布于 2023-02-03 09:20

我对pandas to_datetime函数和pandas中的日期时间有一些困难.具体来说,to_datetime在应用于pandas系列时无声地失败,没有做任何事情,我必须单独显式迭代每个值以使函数正常工作,即使(至少根据这个SO问题)两者都应该工作相同.

In [81]: np.__version__
Out[81]: '1.6.1'

In [82]: pd.__version__
Out[82]: '0.12.0'

In [83]: a[0:10]
Out[83]: 
0    8/31/2013 14:57:00
1    8/31/2013 13:55:00
2    8/31/2013 15:45:00
3     9/1/2013 13:26:00
4     9/1/2013 13:56:00
5     9/2/2013 13:55:00
6     9/3/2013 13:33:00
7     9/3/2013 14:11:00
8     9/3/2013 14:35:00
9     9/4/2013 14:28:00
Name: date_time, dtype: object

In [84]: a[0]
Out[84]: '8/31/2013 14:57:00'

In [85]: a=pd.to_datetime(a)

In [86]: a[0]
Out[86]: '8/31/2013 14:57:00'

In [87]: a=[pd.to_datetime(date) for date in a]

In [88]: a[0]
Out[88]: Timestamp('2013-08-31 14:57:00', tz=None)

有什么想法吗?我似乎总是遇到这个数据并且没有正确解析date_time列的麻烦,我怀疑它可能与此失败有关.

谢谢,

戴夫

1 个回答
  • 这已在新熊猫中修复,默认错误kwarg是“ raise”而不是“ ignore”。
    新的行为是:

    In [21]: pd.to_datetime(dates)  # same as errors='raise'
    ...
    ValueError: Given date string not likely a datetime.
    
    In [22]: pd.to_datetime(dates, errors="ignore")  # the original problem
    Out[22]:
    0    1/1/2014
    1           A
    dtype: object
    

    也就是说,to_datetime不再默默地失败!

    旧答案保留在下面...


    正如DaveA指出的那样(检查我的评论后),默认情况下,to_datetime在出现问题时会静默失败,并返回最初传递的内容:

    In [1]: dates = pd.Series(['1/1/2014', 'A'])
    
    In [2]: pd.to_datetime(dates)  # doesn't even convert first date
    Out[2]: 
    0    1/1/2014
    1           A
    dtype: object
    
    In [3]: pd.to_datetime(dates, errors='raise')
    ...
    ValueError: Given date string not likely a datetime.
    

    注意:此参数以前coerce=True在较早的熊猫版本中使用。

    In [4]: pd.to_datetime(dates, errors='coerce')
    Out[4]: 
    0   2014-01-01
    1          NaT
    dtype: datetime64[ns]
    

    to_datetime在文档的“时间序列”部分中讨论了此行为。

    您可以通过检查查看哪些日期无法解析isnull

    In [5]: dates[pd.isnull(pd.to_datetime(dates, errors='coerce'))]
    Out[5]: 
    1    A
    dtype: object
    

    2023-02-03 09:24 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有