python获取⽇期数组_python-将⽇期时间字段添加到RecArray 我试图将⽇期时间字段(datetime64)附加到现有的Recarray-没有太⼤的成功.我可以创建datetime字段,但是当我尝试将其追加到记录数组时,出现错误:
ValueError:解析⽇期时间字符串“?”时出错在位置0
但是,如果将数据强制转换为int64,则可以毫⽆问题地以该格式添加数据. (代码如下所⽰)
有⼈知道为什么这⾏不通吗?
(我的最终⽬标是将recarray写⼊netcdf⽂件,因此牢记该⽬标的适当⽇期时间格式也将有所帮助)
我正在使⽤python 2.7.6.1,numpy 1.8.1
谢谢,罗伯import numpy as np
import functions as rf
# ----- make a recarray ---------
dummy = np.arange(0,10)
datarray = ds.fromarrays([dummy,dummy,dummy],names='a,b,c')
# ----- make some time data using datetime64 ---------
sec = np.arange(0,10)*1000
millisec = np.arange(0,10)
mytime = sec millisec
mytime64 = mytime.astype('timedelta64[ms]')
basetime = np.datetime64('1990-01-01')
mydatetime = mytime64 basetime
# ----- convert time data to int64 ---------
idatetime = mydatetime.astype('int64');
#------ try and append to recarray ---------
# this works
datarray = rf.append_fields(datarray, 'iDateTime', data=idatetime)
# this doesnt
datarray = rf.append_fields(datarray, 'DateTime', data=mydatetime)
解决⽅法:
追溯为:Traceback (most recent call last):
python获取数组长度File "stack26739733.py", line 30, in
datarray = rf.append_fields(datarray, 'DateTime', data=mydatetime, usemask=False, dtypes=mydatetime.dtype)
File "/usr/local/lib/python2.7/site-packages/numpy/lib/recfunctions.py", line 641, in append_fields
dtype=base.dtype.descr data.dtype.descr)
File "/usr/local/lib/python2.7/site-packages/numpy/ma/extras.py", line 163, in masked_all
s(shape, make_mask_descr(dtype)))
File "/usr/local/lib/python2.7/site-packages/numpy/ma/core.py", line 2644, in __new__
_data = ndarray.view(_data, cls)
File "/usr/local/lib/python2.7/site-packages/numpy/ma/core.py", line 2800, in __array_finalize__
self._fill_value = _check_fill_value(None, self.dtype)
File "/usr/local/lib/python2.7/site-packages/numpy/ma/core.py", line 402, in _check_fill_value
dtype=ndtype,)
ValueError: Error parsing datetime string "?" at position 0
因此,此附加函数构造了⼀个掩码数组(ma),并检查了附加值“ dtype”的“ fill_value”.显然_check_fill_value不了解datetime dtype.看起来好像是掩码数组和⽇期时间之间的不兼容.可能有⼀些numpy错误报告.
这是⼀个简单的⾃⼰动⼿的附件:dt1 = np.dtype(datarray.dtype.descr mydatetime.dtype.descr)
newarray = np.empty(datarray.shape, dtype=dt1)
for n in datarray.dtype.names:
newarray[n] = datarray[n]
newarray['f3'] = mydatetime
我⽤联合dtype构造⼀个空数组.然后,我逐字段地同时从datarray和mydatetime复制数据.由于与形状相⽐,字段数通常很⼩,因此此副本⾮常快.我很确定rf函数的作⽤相同.
“ f3”是添加字段的默认名称.您可以在创建dt1时更改它.
结果是:array([(0, 0, 0, datetime.datetime(1990, 1, 1, 0, 0)),
(1, 1, 1, datetime.datetime(1990, 1, 1, 0, 0, 1, 1000)),
(2, 2, 2, datetime.datetime(1990, 1, 1, 0, 0, 2, 2000)),
...
(9, 9, 9, datetime.datetime(1990, 1, 1, 0, 0, 9, 9000))],
dtype=[('a', '
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论