首页 > 解决方案 > 如何将 numpy 数组从 numpy.int64 转换为 datetime?

问题描述

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

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

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

如果我错了,请纠正我。

PS这个问题可能已经在某个地方得到了回答,但我找不到一个可行的解决方案。

标签: pythonpython-3.xnumpydatetime

解决方案


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)
...

它足够高效。


推荐阅读