2016-08-15 81 views
1

我試圖儘可能快地使用花式索引從大的numpy數組中切片。我會很高興返回一個視圖,但advanced indexing returns a copy在numpy中快速高級索引

我已經嘗試過herehere的解決方案,目前爲止沒有喜悅。

玩具數據:

data = np.random.randn(int(1e6), 50) 
keep = np.random.rand(len(data))>0.5 

使用默認方法:

%timeit data[keep] 
10 loops, best of 3: 86.5 ms per loop 

numpy的採取:

%timeit data.take(np.where(keep)[0], axis=0) 
%timeit np.take(data, np.where(keep)[0], axis=0) 
10 loops, best of 3: 83.1 ms per loop 
10 loops, best of 3: 80.4 ms per loop  

方法從here

rows = np.where(keep)[0] 
cols = np.arange(a.shape[1]) 
%timeit (a.ravel()[(cols + (rows * a.shape[1]).reshape((-1,1))).ravel()]).reshape(rows.size, cols.size) 
10 loops, best of 3: 159 ms per loop 

而如果你採取同樣大小的一個觀點:

%timeit data[1:-1:2, :] 
1000000 loops, best of 3: 243 ns per loop 

回答

5

有沒有辦法,以期做到這一點。一個視圖需要一致的邁進,而你的數據是隨機分散在整個原始數組中的。

+0

夠公平 - 我不一定會被視爲一種視圖,任何一種加速都會很棒。謝謝! – dgmp88

+1

您是否期望一些新的東西,這在http://stackoverflow.com/questions/14386822/fast-numpy-fancy-indexing中沒有涉及? – hpaulj

+0

是的,我希望有一些不同的東西 - 這些解決方案在這種情況下工作得很好,因爲它們在行和列上切片,所以輸出矩陣要小得多。在這裏,我只是在行上切片,最後輸出很大。 – dgmp88