2017-09-03 33 views
2

NumPy數組可能與其他數組建立索引。爲了說明:從給出開始索引的1D數組中提取子陣列 - Python/NumPy

>>> import numpy as np 

>>> arr = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0et ], 'f4') 
>>> ids = np.array([0, 2], 'i4') 
arr[ids] 
array([ 0., 2.], dtype=float32) 

但如果我想與由索引加上三個subsequents元素所指向的值多陣列?

>>> arr[ids:(ids+4)] 
Traceback (most recent call last): 
    File "<console>", line 1, in <module> 
IndexError: invalid slice 

預計:

array([[0. 1. 2. 3.], [2. 3. 4. 5.]], dtype=float32) 

如何實現這一目標?

+0

能否請您解釋一下你想獲得什麼陣列?預期的產出? –

+0

感謝您的消化,我添加了預期的輸出 –

+0

我想你或者在每個預期輸出的子陣列中都有一個兩個元素,或者其他的意思是'arr [ids:(ids + 4)]',對吧? – jdehesa

回答

3

使用broadcasted除了創建所有這些索引,然後指數 - 基於strided_app

all_idx = ids[:,None]+range(4) # or np.add.outer(ids, range(4)) 
out = arr[all_idx] 

使用np.lib.stride_tricks.as_strided -

strided_app(arr, 4, S=1)[ids] 
+0

嗯,其實可以解決!在標記爲答案之前,我會等待第二個建議;) –

相關問題