首页 > 解决方案 > 如何将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)

以优化速度的方式?

标签: pythonpandasnumpy

解决方案


让我们回顾一下文档

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

推荐阅读