我有以下numpy的結構化陣列:查看與偏移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')])
下面的陣列是上述陣列的一個子集(也景色):
我試圖將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]])
查看鑄造似乎當字段是不連續到不行,有沒有替代?
太棒了!謝謝。 – snowleopard
這個字段必須持續工作嗎? ['f4','f1']從我的理解中仍然是連續的。這就是爲什麼這個主張在那裏。 – snowleopard
嘗試'fields = ['f4','f3','f1']'。偏移是'[12,8,0]' - 有-4和-8的差距。 「步伐」不能同時處理兩者。 – hpaulj