【问题标题】:Specifying a strftime format to speed up pandas' to_datetime() method指定 strftime 格式以加快 pandas 的 to_datetime() 方法
【发布时间】:2016-07-14 20:25:42
【问题描述】:

考虑以下代码:

import pandas as pd
some_time='01/01/2011 12:02:41 AM'
print(pd.to_datetime(some_time))
print(pd.to_datetime(some_time, format='%m/%d/%Y %I:%M:%S %r'))

第一个to_datetime() 转换工作并打印输出

2011-01-01 00:02:41

不幸的是,在我的实际应用程序中,我正在处理一个包含超过 200 万行的 DataFrame,并且默认的 to_datetime() 速度非常慢,即使我在关键字参数中设置了 infer_datetime_format=True

我读到to_datetime() 可以通过明确指定字符串格式来加速。我在http://www.tutorialspoint.com/python/time_strftime.htm 之后尝试过这个,但是我上面的尝试失败并出现错误ValueError: 'r' is a bad directive in format '%m/%d/%Y %I:%M:%S %r'

如何指定正确的 strftime 格式以将'01/01/2011 12:02:41 AM' 转换为日期时间?

【问题讨论】:

    标签: python pandas strftime


    【解决方案1】:

    我认为您只需要%p 而不是%r。区别在于%r 需要标点符号(上午或下午),而%p 不需要(上午或下午)。

    当我进行更改时,您的代码不会产生任何错误:

    pd.to_datetime(some_time, format='%m/%d/%Y %I:%M:%S %p')
    

    【讨论】:

      【解决方案2】:

      root 在评论中给出了正确答案。为了完整起见,%r 需要替换为%p

      some_time='01/01/2011 12:02:41 AM'
      print(pd.to_datetime(some_time))
      print(pd.to_datetime(some_time, format='%m/%d/%Y %I:%M:%S %p'))
      

      这会产生输出

      2011-01-01 00:02:41
      2011-01-01 00:02:41
      

      也就是说,带有和不带有 format 关键字参数的相同输出。

      【讨论】:

        猜你喜欢
        • 2023-02-10
        • 2020-12-11
        • 2016-08-19
        • 2019-03-01
        • 2018-10-06
        • 1970-01-01
        • 2016-04-03
        • 2020-08-15
        • 2021-03-22
        相关资源
        最近更新 更多