2013-10-20 19 views
-1

我有一個一維數組,我想從中創建一個新的數組,其中只包含用戶希望大小的開始,中間和前者的部分。numpy slicing選擇部分數組

import numpy 
a = range(10) 
a 
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) 

我想b鍵等於:

b 
array([0, 1, 2, 5, 6, 7, 9]) 

假設b的構造的的串聯的[3],A [5:6],並且[9] 。 我當然可以使用諸如np.concatenate之類的東西,但是有沒有辦法用切片方法來做到這一點,或者是否有其他方法在一行中執行?

+2

它真的很難理解你要求什麼。 –

回答

1

一種方法是創建要索引的索引數組與數組:

import numpy 
a = numpy.arange(10) 
i = numpy.array([0, 1, 2, 5, 6, 7, 9]) # An array containing the indices you want to extract 
print a[i] # Index the array based on the indices you selected 

輸出

[0 1 2 5 6 7 9] 
+0

我忘了提及我追求的解決方案應該可以在100個元素的數組中工作。 – user1850133

0

我找到了一個解決方案:

import numpy as np 
a = range(10) 
b = np.hstack([a[:3], a[5:6], a[9]) 
b 
array([0, 1, 2, 5, 6, 7, 9]) 

但切片是否允許這樣的動作?