我有以下 numpy 结构化数组:
In [250]: x
Out[250]:
array([(22, 2, -1000000000, 2000), (22, 2, 400, 2000),
(22, 2, 804846, 2000), (44, 2, 800, 4000), (55, 5, 900, 5000),
(55, 5, 1000, 5000), (55, 5, 8900, 5000), (55, 5, 11400, 5000),
(33, 3, 14500, 3000), (33, 3, 40550, 3000), (33, 3, 40990, 3000),
(33, 3, 44400, 3000)],
dtype=[('f1', '<i4'), ('f2', '<i4'), ('f3', '<i4'), ('f4', '<i4')])
下面的数组是上面数组的一个子集(也是一个视图):
In [251]: fields=['f1','f3']
In [252]: y=x.getfield(np.dtype(
...: {name: x.dtype.fields[name] for name in fields}
...: ))
In [253]: y
Out[253]:
array([(22, -1000000000), (22, 400), (22, 804846), (44, 800), (55, 900),
(55, 1000), (55, 8900), (55, 11400), (33, 14500), (33, 40550),
(33, 40990), (33, 44400)],
dtype={'names':['f1','f3'], 'formats':['<i4','<i4'], 'offsets':[0,8], 'itemsize':12})
我正在尝试将 y 转换为常规的 numpy 数组。我希望数组是一个视图。问题是以下给了我一个错误:
In [254]: y.view(('<i4',2))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-254-88440f106a89> in <module>()
----> 1 y.view(('<i4',2))
C:\numpy\core\_internal.pyc in _view_is_safe(oldtype, newtype)
499
500 # raises if there is a problem
--> 501 _check_field_overlap(new_fieldtile, old_fieldtile)
502
503 # Given a string containing a PEP 3118 format specifier,
C:\numpy\core\_internal.pyc in _check_field_overlap(new_fields, old_fields)
402 old_bytes.update(set(range(off, off+tp.itemsize)))
403 if new_bytes.difference(old_bytes):
--> 404 raise TypeError("view would access data parent array doesn't own")
405
406 #next check that we do not interpret non-Objects as Objects, and vv
TypeError: view would access data parent array doesn't own
但是,如果我选择连续的字段,它会起作用:
In [255]: fields=['f1','f2']
...:
...: y=x.getfield(np.dtype(
...: {name: x.dtype.fields[name] for name in fields}
...: ))
...:
In [256]: y
Out[256]:
array([(22, 2), (22, 2), (22, 2), (44, 2), (55, 5), (55, 5), (55, 5),
(55, 5), (33, 3), (33, 3), (33, 3), (33, 3)],
dtype=[('f1', '<i4'), ('f2', '<i4')])
In [257]: y.view(('<i4',2))
Out[257]:
array([[22, 2],
[22, 2],
[22, 2],
[44, 2],
[55, 5],
[55, 5],
[55, 5],
[55, 5],
[33, 3],
[33, 3],
[33, 3],
[33, 3]])
当字段不连续时,视图转换似乎不起作用,是否有替代方法?