更新时间:2022-06-10 00:08:57
所以
In [112]: x_values
Out[112]:
array([( 0, 0), ( 50, 5), (100, 10)],
dtype=[('seconds', '<i8'), ('nanos', '<i4')])
除非您需要特殊行为,否则我通常不建议使用nditer
.通常只需要对数组进行简单迭代(如果为2d,则为行).但是,为了更好地了解正在发生的事情,让我们比较一下迭代方法:
I don't usually recommend using nditer
unless you need special behavior. Simple iteration on the array (rows if 2d) is usually all you need. But to better understand what is happening, lets compare the iteration methods:
In [114]: for elem in np.nditer(x_values):
...: print(elem, elem.dtype)
...: print(type(elem))
(0, 0) [('seconds', '<i8'), ('nanos', '<i4')]
<class 'numpy.ndarray'>
(50, 5) [('seconds', '<i8'), ('nanos', '<i4')]
<class 'numpy.ndarray'>
(100, 10) [('seconds', '<i8'), ('nanos', '<i4')]
<class 'numpy.ndarray'>
In [115]: for elem in x_values:
...: print(elem, elem.dtype)
...: print(type(elem))
(0, 0) [('seconds', '<i8'), ('nanos', '<i4')]
<class 'numpy.void'>
(50, 5) [('seconds', '<i8'), ('nanos', '<i4')]
<class 'numpy.void'>
(100, 10) [('seconds', '<i8'), ('nanos', '<i4')]
<class 'numpy.void'>
除type
以外,与其他相同,np.ndarray
v.np.void
.修改nditer
变量更容易.
Same except the type
is different, np.ndarray
v. np.void
. It's easier to modify the nditer
variable.
执行相同操作,但只查看一个字段:
Do the same but looking at one field:
In [119]: for elem in np.nditer(x_values):
...: print(elem['seconds'], type(elem['seconds']))
0 <class 'numpy.ndarray'>
50 <class 'numpy.ndarray'>
100 <class 'numpy.ndarray'>
In [120]: for elem in x_values:
...: print(elem['seconds'], type(elem['seconds']))
0 <class 'numpy.int64'>
50 <class 'numpy.int64'>
100 <class 'numpy.int64'>
我没有protobuf
代码,但我怀疑
ts2.seconds = elem['seconds']
在第二次迭代中会更好地工作,第二次迭代会生成np.int64
值.或添加elem['seconds'].item()
.
will work better with the 2nd iteration, the one that produces np.int64
values. Or add elem['seconds'].item()
.