无法填充NumPy datetime64数组 [英] Cannot populate NumPy datetime64 arrays

查看:232
本文介绍了无法填充NumPy datetime64数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个NumPy数组,该数组随后将由一些日期时间值填充.我似乎无法使其正常工作.

I'm trying to create a NumPy array that will subsequently be populated by some datetime values. I can't seem to make it work.

import numpy as np
t = np.empty(3,dtype='datetime64')
t

我得到一个TypeError: Invalid datetime unit "generic" in metadata.
如果我尝试的话也一样:

I get a TypeError: Invalid datetime unit "generic" in metadata.
Same if I try :

import numpy as np
t = np.empty(3,dtype='datetime64')
t[0] = np.datetime64('2014-12-12 20:20:20')

我得到:

TypeError : Cannot cast numpy timedelta64 scalar from metadata [m] to  according to the rule 'same_kind'

推荐答案

如果在创建数组时还指定了时间单位参数,则它应该可以工作.例如:

It should work if you also specify a time unit parameter when creating the array. For example:

>>> t = np.empty(3, dtype='datetime64[s]')
>>> t
array(['1970-01-01T00:00:00+0000', '1970-01-01T00:00:00+0000',
       '1970-01-01T00:00:00+0000'], dtype='datetime64[s]')

然后您还可以根据需要分配值:

And then you can also assign the values as required:

>>> t[0] = np.datetime64('2014-12-12 20:20:20')
>>> t
array(['2014-12-12T20:20:20+0000', '1970-01-01T00:00:00+0000',
       '1970-01-01T00:00:00+0000'], dtype='datetime64[s]')

NumPy不允许使用通用单位(即无单位)表示日期时间.创建不带unit参数的数组t,然后尝试访问第一个元素t[0]会引发此错误:

NumPy doesn't permit datetimes with generic units (i.e. no units) to be represented. Creating the array t without the unit parameter and then trying to access the first element t[0] will raise this error:

ValueError: Cannot convert a NumPy datetime value other than NaT with generic units

在这里,NumPy无法推断日期时间表示应具有的单位.考虑到日历月份和年份的长度不同,猜测可能会导致错误的值.

Here, NumPy isn't able to infer what units the representation of the datetime should have. Guessing might lead to erroneous values given the varying lengths of calendar months and years.

这点在文档中不是很明确,但是可以从此处.

This point isn't very explicit in the documentation but can be gleaned from the datetime page and is noted in the source code here.

这篇关于无法填充NumPy datetime64数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆