[英]Numpy structured array with datetime
I tried to build a structured array with a datetime coloumn 我试图用日期时间列来构建结构化数组
import numpy as np
na_trades = np.zeros(2, dtype = 'datetime64,i4')
na_trades[0] = (np.datetime64('1970-01-01 00:00:00'),0)
TypeError: Cannot cast NumPy timedelta64 scalar from metadata [s] to according to the rule 'same_kind'
Is there a way to fix this? 有没有办法解决这个问题?
You have to specify that the datetime64
is in seconds when you create the array because the one you parse and try to assign is a datetime64[s]
: 创建数组时,您必须指定
datetime64
以秒为单位,因为您解析并尝试分配的数组是datetime64[s]
:
na_trades = np.zeros(2, dtype='datetime64[s],i4')
na_trades[0] = (np.datetime64('1971-01-01 00:00:00'), 0)
The error you get means that the datetime64
object that you specified is not same_kind
as the one you try to assing. 您得到的错误意味着您指定的
datetime64
对象与您尝试的对象不是same_kind
。 You try to assign a seconds resolution one, and you created a different one when you constructed the array (by default I think it's nanoseconds). 您尝试分配一个秒分辨率,然后在构造数组时创建了另一个分辨率(默认情况下,我认为是纳秒)。
Try following: 尝试以下操作:
>>> na_trades = np.zeros(2, dtype=[('dt', 'datetime64[s]'), ('vol', 'i4')])
>>> na_trades
array([(datetime.datetime(1970, 1, 1, 0, 0), 0),
(datetime.datetime(1970, 1, 1, 0, 0), 0)],
dtype=[('dt', ('<M8[s]', {})), ('vol', '<i4')])
>>> na_trades[0] = (np.datetime64('1970-01-02 00:00:00'),1)
>>> na_trades
array([(datetime.datetime(4707, 11, 29, 0, 0), 1),
(datetime.datetime(1970, 1, 1, 0, 0), 0)],
dtype=[('dt', ('<M8[s]', {})), ('vol', '<i4')])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.