【问题标题】:Inserting a datetime value within a datetime array Numpy Python在日期时间数组 Numpy Python 中插入日期时间值
【发布时间】:2022-01-03 02:21:35
【问题描述】:

我想在数组as 的第一个索引中插入日期'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']

【问题讨论】:

    标签: python numpy date datetime indexing


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      在像hstack 这样的情况下,您希望首先将此字符串转换为正确的 dtype,但insert 确实会为您处理这些问题。它有一行:

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

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

      【讨论】:

        猜你喜欢
        • 2013-11-21
        • 2016-07-05
        • 2021-03-22
        • 2016-01-21
        • 1970-01-01
        • 1970-01-01
        • 2015-01-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多