在日期时间数组Numpy Python中插入日期时间值



我想在数组a的第一个索引中插入日期'2015-12-24 12:51:00'作为日期时间值。如何才能做到这一点并获得预期输出。到日期时间数组a

import numpy as np 
import datetime 
a = np.array(['2017-09-15 07:11:00', '2017-09-15 12:11:00', '2017-12-22 03:26:00',
 '2017-12-22 03:56:00', '2017-12-22 20:59:00', '2017-12-24 12:51:00'], dtype='datetime64[ns]')
datetime = np.insert(a, 0, ('2015-12-24 12:51:00',dtype='datetime64[ns]'))

错误消息:

  File "<ipython-input-5-ac3ba1f95707>", line 6
    datetime = np.insert(a, 0, ('2015-12-24 12:51:00',dtype='datetime64[ns]'))
                                                           ^
SyntaxError: invalid syntax

预期输出:

['2015-12-24T12:51:00.000000000' '2017-09-15T07:11:00.000000000'
 '2017-09-15T12:11:00.000000000' '2017-12-22T03:26:00.000000000'
 '2017-12-22T03:56:00.000000000' '2017-12-22T20:59:00.000000000'
 '2017-12-24T12:51:00.000000000']

您不需要在insert上指定dtype,这基本上就是您得到的错误所说的。只做np.insert(a, 0, ('2015-12-24 12:51:00'))

来源:https://numpy.org/doc/stable/reference/generated/numpy.insert.html

np.array('2015-12-24 12:51:00',dtype='datetime64[ns]')是创建日期时间数组的正确语法。dtype是用于np.array函数的关键字参数。

在像hstack这样的情况下,您希望首先将此字符串强制转换为正确的dtype,但insert确实会帮您解决这一问题。它有一条线:

values = array(values, copy=False, ndmin=arr.ndim, dtype=arr.dtype)

当然,自己进行转换没有害处,只需使用正确的语法即可。