【问题标题】:How to convert numpy array from numpy.int64 to datetime?如何将 numpy 数组从 numpy.int64 转换为 datetime?
【发布时间】:2019-05-11 15:37:50
【问题描述】:

我有以下<class 'numpy.ndarray'> 类型的数组

array([20181010, 20181031, 20181116, 20181012, 20181005, 20181008,
       20181130, 20181011, 20181005, 20181116])

如何将其成分从当前类型<class 'numpy.int64'> 转换为numpy 中的日期时间?我想找到一种快速的方法,我的理解是使用循环或列表理解,以及将此 numpy.array 转换为 pandaslist 会更慢。

如果我错了,请纠正我。

附:这个问题可能已经在某处得到解答,但我找不到一个可行的解决方案。

【问题讨论】:

  • @Nixon,但那里的答案并不理想。肯定有更好的目标吗?
  • 我认为@Sebastian's answer is superior to the duplicate, https://stackoverflow.com/questions/27103044/converting-datetime-string-to-datetime-in-numpy-python, even though both use pd.to_datetime`。
  • @hpaulj 我尝试了重复,我尝试了塞巴斯蒂安的回答,事实上我也同意你的观点。因此,我投票并标记为正确的原因(以及为什么我在提问时无法从标记为重复的内容中得到完整的答案)。

标签: python python-3.x numpy datetime


【解决方案1】:

pandas 对什么可以被视为日期有更好的概念:

import numpy as np
import pandas as pd
arr = np.array([20181010, 20181031, 20181116, 20181012, 20181005, 
                20181008, 20181130, 20181011, 20181005, 20181116])
pd.to_datetime(arr.astype(str)).values

在一组 10,000,000 个条目上运行:

%%prun import numpy as np; import pandas as pd
lst = [20181010, 20181031, 20181116, 20181012, 20181005, 
       20181008, 20181130, 20181011, 20181005, 20181116]*1000000
arr = np.array(lst)
arr_str = arr.astype(str)
pd.to_datetime(arr_str).values

产生一个prun

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    8.977    8.977    8.977    8.977 {method 'astype' of 'numpy.ndarray' objects}
        1    4.394    4.394    4.394    4.394 {built-in method pandas._libs.tslib.array_to_datetime}
        2    2.344    1.172    2.344    1.172 {built-in method pandas._libs.algos.ensure_object}
        4    0.918    0.229    0.918    0.229 {built-in method numpy.core.multiarray.array}
        1    0.313    0.313    7.053    7.053 datetimes.py:106(to_datetime)
...

足够高效。

【讨论】:

  • 从时间上看,转换为 pandas 的结果如何?另外,我希望将np.array 作为最终结果。这会很昂贵吗?
  • 不,pandas 也像 numpy 一样矢量化了;查看我的编辑。
  • pandas 在 Python 迭代中做了很多事情。 vectorized 是一个狡猾的术语。为了加快速度,需要编译底层代码,而不需要对 Python 类和对象进行大量重复调用。
  • prun 中,我没有看到任何函数被调用 10,000,000 次,正如人们所期望的那样,通过创建 10,000,000 个日期时间对象。这让我相信 pandas 确实通过某种程度的编译。
  • 这实际上产生了np.datetime[ns] dtype 数组。这可能是你想要的。但如果你真的想要 datetime.date 对象,你需要一个额外的步骤:.astype('datetime64[D]').tolist()
猜你喜欢
  • 1970-01-01
  • 2015-06-27
  • 2019-03-29
  • 2021-12-18
  • 2015-12-12
  • 2021-06-09
  • 1970-01-01
  • 2020-05-04
  • 1970-01-01
相关资源
最近更新 更多