python - 如何将int数组转换回熊猫时间戳?
问题描述
我能够将类型pandas timestamp
为 numpy-array 的列转换为 int 数组:
import numpy as np
import pandas as pd
df = pd.DataFrame({'a': [pd.datetime(2019, 1, 11, 5, 30, 1), pd.datetime(2019, 1, 11, 5, 30, 1), pd.datetime(2019, 1, 11, 5, 30, 1)], 'b': [np.nan, 5.1, 1.6]})
a = df.to_numpy()
a
# array([[Timestamp('2019-01-11 05:30:01'), nan],
# [Timestamp('2019-01-11 05:30:01'), 5.1],
# [Timestamp('2019-01-11 05:30:01'), 1.6]], dtype=object)
a[:,0] = a[:,0].astype('datetime64').astype(np.int64)
# array([[1547184601000000, nan],
# [1547184601000000, 5.1],
# [1547184601000000, 1.6]], dtype=object)
对于这个数组 a,我想将第 0 列转换回熊猫时间戳。由于数组非常大,而且我的整个过程非常耗时,我想避免使用 python 循环、应用程序、lambdas 或类似的东西。相反,我正在寻找速度优化的基于 numpy 的原生函数等。
我已经尝试过类似的东西:
a[:,0].astype('datetime64')
(结果ValueError: Converting an integer to a NumPy datetime requires a specified unit
:)
和:
import calendar
calendar.timegm(a[:,0].utctimetuple())
(结果AttributeError: 'numpy.ndarray' object has no attribute 'utctimetuple'
:)
如何将我的列转换a[:,0]
回
array([[Timestamp('2019-01-11 05:30:01'), nan],
[Timestamp('2019-01-11 05:30:01'), 5.1],
[Timestamp('2019-01-11 05:30:01'), 1.6]], dtype=object)
以优化速度的方式?
解决方案
让我们回顾一下文档
datetime64 数据的不可变 ndarray,内部表示为 int64,可以装箱到 Timestamp 对象,这些对象是 datetime 的子类并携带诸如频率信息之类的元数据。
所以,我们可以使用DatetimeIndex
. 然后使用np.int64
.
In [18]: b = a[:,0]
In [19]: index = pd.DatetimeIndex(b)
In [21]: index.astype(np.int64)
Out[21]: Int64Index([1547184601000000000, 1547184601000000000, 1547184601000000000], dtype='int64')
推荐阅读
- rundeck - rundeck 工作流程的行为,带有“在失败的步骤处停止”和“并行策略”
- python - 如果值有新数据,则迭代熊猫数据框的列填充
- c# - 将 Level 设置为具有多个层的嵌套列表
- r - ggplot中带有单列的堆叠条形图?
- python-3.x - DBSCAN 返回 TypeError:无效的类型提升
- angular - forkJoin 内部的角度单元测试
- jupyter-notebook - ipywidgets Widget - 日期选择器 - Mozilla Firefox 的问题
- mysql - 从一组表数据生成/设计一个 json 对象
- reactjs - Botpress - 自定义组件访问会话变量
- firebase - 构建 React Native Firebase 应用程序时 MyApplication.java 中的错误