python - 如何将 numpy 数组从 numpy.int64 转换为 datetime?
问题描述
我有以下类型的数组<class 'numpy.ndarray'>
array([20181010, 20181031, 20181116, 20181012, 20181005, 20181008,
20181130, 20181011, 20181005, 20181116])
如何将其成分从当前类型转换<class 'numpy.int64'>
为日期时间numpy
?我想找到一种快速的方法,我的理解是使用循环或列表理解,以及将其转换numpy.array
为pandas
或转换为 alist
会更慢。
如果我错了,请纠正我。
PS这个问题可能已经在某个地方得到了回答,但我找不到一个可行的解决方案。
解决方案
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)
...
它足够高效。
推荐阅读
- flutter - 颤动删除特定页面的标签栏
- socat - 是否可以使用 socat 打开现有的 tun 设备而不是创建新设备?
- mysql - 如何在groupby mysql之后获得最大值
- javascript - 在 Bootstrap 中单击时将卡片变灰
- javascript - 奇怪的行为: if( 取布尔值 false
- javascript - 与 node-gyp 相关的电子生成器错误
- vb.net-2010 - 在 Source Bitmap 和 BitmapData 中声明 Format32BppArgb 时,Lockbits 返回一个意外的(对我而言)Stride 值
- .net - .net Framework 3.5 版本中的 PropertyGrid 绘制异常
- android - DRM/KMS 禁用连接器和 crtc
- typescript - 键入'{ localUUID:字符串;}' 不可分配给类型 'string | 正则表达式'