Python 如何将int数组转换回时间戳?

Python 如何将int数组转换回时间戳?,python,pandas,numpy,Python,Pandas,Numpy,我能够将pandas timestamp类型的numpy数组列转换为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.t

我能够将
pandas timestamp
类型的numpy数组列转换为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循环、apply、lambda或类似的东西。相反,我正在寻找速度优化的基于numpy的本机函数等

我已经试过了,比如:

a[:,0].astype('datetime64')
(结果:
ValueError:将整数转换为NumPy日期时间需要指定的单位

以及:

(结果:
AttributeError:'numpy.ndarray'对象没有属性“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数据的不可变数据数组,内部表示为int64,可以装箱到作为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')

“返回”是什么意思?我看不出您的原始数据与所需输出之间的差异?我的意思是从带有
int
s('1547184601000000'等)的列中得到的“返回”返回到时间戳(
'2019-01-11 05:30:01'
)谢谢,这非常有用。但是,您必须在1000之前多倍运算,才能得到正确的结果:
pd.DatetimeIndex(a[:,0]*1e3)
可以装箱到
-这意味着什么?@wwii要解释您的问题,我想您应该检查链接
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')