[英]View of numpy structured array with offsets
我有以下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]])
當字段不連續時,視圖轉換似乎不起作用,是否有替代方法?
是的,直接使用ndarray
構造函數:
x = np.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)],
dtype=[('f1','i'),('f2','i'),('f3','i'),('f4','i')])
fields = ['f4', 'f1']
shape = x.shape + (len(fields),)
offsets = [x.dtype.fields[name][1] for name in fields]
assert not any(np.diff(offsets, n=2))
strides = x.strides + (offsets[1] - offsets[0],)
y = np.ndarray(shape=shape, dtype='i', buffer=x,
offset=offsets[0], strides=strides)
print repr(y)
給出:
array([[2000, 22],
[2000, 22],
[2000, 22],
[4000, 44],
[5000, 55],
[5000, 55]])
順便說一句,當原始數組中的所有字段都具有相同的dtype時,首先在該數組上創建視圖然后進行切片操作會容易得多。 對於與上述相同的結果:
y = x.view('i').reshape(x.shape + (-1,))[:,-1::-3]
以下內容有些令人困惑-但是要點是,要使這種view
起作用,它必須能夠以規則的步幅和形狀訪問字段。 從['f1','f3']獲取視圖失敗的原因基本上與np.ones((12,4))[:,[0,2]]
產生副本的原因相同。
========
在結構化數組中,每個記錄都存儲為4 *'i4'字節。 該布局與(n,4)'i4'數組兼容:
In [381]: x.__array_interface__['data'] # databuffer pointer
Out[381]: (160925352, False)
In [382]: x.view(('i',4)).__array_interface__['data']
Out[382]: (160925352, False) # same buffer
In [387]: x.view(('i',4)).shape
Out[387]: (12, 4)
但是當我把這個數組切成薄片時
In [383]: x.view(('i',4))[:,[0,1]].__array_interface__['data']
Out[383]: (169894184, False) # advance indexing - a copy
In [384]: x.view(('i',4))[:,:2].__array_interface__['data']
Out[384]: (160925352, False) # same buffer
但是選擇['f1','f3']等效於: x.view(('i',4))[:,[0,2]]
,另一個副本。
或看看大步前進。 與第一個2個字段
In [404]: y2=x.getfield(np.dtype({name: x.dtype.fields[name] for name in ['f1','f2']}))
In [405]: y2.dtype
Out[405]: dtype([('f1', '<i4'), ('f2', '<i4')])
In [406]: y2.strides
Out[406]: (16,)
In [407]: y2.view(('i',2)).strides
Out[407]: (16, 4)
要將數組看成整數,可以對行進行16步步進,對列進行4步步進,僅占用2列。
或者查看4列和2列案例的完整詞典
In [409]: x.view(('i',4)).__array_interface__
Out[409]:
{'data': (160925352, False),
'descr': [('', '<i4')],
'shape': (12, 4),
'strides': None,
'typestr': '<i4',
'version': 3}
In [410]: y2.view(('i',2)).__array_interface__
Out[410]:
{'data': (160925352, False),
'descr': [('', '<i4')],
'shape': (12, 2),
'strides': (16, 4),
'typestr': '<i4',
'version': 3}
大步和dtype相同,只是形狀不同。 y2
情況之所以有效,是因為它可以跨步訪問所需的字節,而忽略2列。
如果我切出4列情況的2個中間列,則會得到一個視圖-相同的數據緩沖區,但具有偏移量:
In [385]: x.view(('i',4))[:,2:4].__array_interface__['data']
Out[385]: (160925360, False)
但是將getfield
與這2個字段一起使用會產生與['f1','f3']相同的錯誤:
In [388]: y2=x.getfield(np.dtype({name: x.dtype.fields[name] for name in ['f2','f3']})).view(('i',2))
...
ValueError: new type not compatible with array.
view
無法實現切片可以實現的數據緩沖區偏移量。
========
再次查看2個中間字段:
In [412]: y2=x.getfield(np.dtype({name: x.dtype.fields[name] for name in ['f2','f3']}))
...:
In [413]: y2
Out[413]:
array([(2, -1000000000), (2, 400), (2, 804846), (2, 800), (5, 900),
(5, 1000), (5, 8900), (5, 11400), (3, 14500), (3, 40550),
(3, 40990), (3, 44400)],
dtype={'names':['f2','f3'], 'formats':['<i4','<i4'], 'offsets':[4,8], 'itemsize':12})
In [414]: y2.__array_interface__['data']
Out[414]: (160925352, False)
y2
指向原始數據庫的開始。 它使用dtype
偏移量實現偏移量。 將其與In[385]
的偏移進行比較。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.