2016-11-18 31 views
1

我有以下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]]) 

查看鑄造似乎當字段是不連續到不行,有沒有替代?

回答

2

是,使用直接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]]) 

順便說一句,當原來的陣列中的所有字段具有相同的D型,它更容易先在該陣列上創建一個視圖,然後進行切片操作。與上面相同的結果:

y = x.view('i').reshape(x.shape + (-1,))[:,-1::-3] 
y = x.view('i').reshape(x.shape + (-1,))[:,-1::-3] 
+0

太棒了!謝謝。 – snowleopard

+0

這個字段必須持續工作嗎? ['f4','f1']從我的理解中仍然是連續的。這就是爲什麼這個主張在那裏。 – snowleopard

+0

嘗試'fields = ['f4','f3','f1']'。偏移是'[12,8,0]' - 有-4和-8的差距。 「步伐」不能同時處理兩者。 – hpaulj

1

以下是有點令人困惑 - 但要點是,這種view工作,它必須能夠訪問具有常規數組步幅和形狀的字段。基於與np.ones((12,4))[:,[0,2]]生成副本基本相同的原因,從['f1','f3']獲取視圖失敗。

========

在您的結構陣列,每個記錄存儲爲4 * '6-14' 字節。該佈局是與第(n,4) '6-14' 陣列兼容:

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} 

同進步和D型,只是不同的形狀。 y2的情況下工作,因爲它可以通過striding訪問所需的字節,並忽略2列。

如果I切片出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不能執行該設置DataBuffer偏移切片即可。

========

在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]中的偏移量進行比較。

+0

感謝您的非常詳細的答案,我期待過程與連續字段一起工作,但我也注意到它只適用於包含第一個字段的切片。我明白,如果字段不連續,則會觸發高級索引並返回副本。我不明白爲什麼它不適用於一些連續的領域,因爲這似乎本質上是一個切片。 – snowleopard

+0

我在f2/f3'切片'上添加了一些信息。兩種方法都需要某種偏移量,但它們使用不同的方法。一個抵消databuffer指針,並從那裏使用常規大步。另一個使用'dtype'偏移量和原始databuffer指針。 – hpaulj