2015-02-23 25 views
0

根據take 的numpy文檔,它與「花哨」索引(使用數組索引數組)做同樣的事情。但是,如果您需要沿給定軸的元素,則使用起來會更容易。numpy take不能使用分片索引

然而,與「幻想」或定期numpy的索引,使用切片作爲指標似乎不支持:

In [319]: A = np.arange(20).reshape(4, 5) 

In [320]: A[..., 1:4] 
Out[320]: 
array([[ 1, 2, 3], 
     [ 6, 7, 8], 
     [11, 12, 13], 
     [16, 17, 18]]) 

In [321]: np.take(A, slice(1, 4), axis=-1) 
TypeError: long() argument must be a string or a number, not 'slice' 

什麼是指數的最佳方式使用片沿軸的陣列只有在運行時知道?

+1

請提供一個可運行的例子,以及你的前回復 – 2015-02-23 22:34:40

+0

有些代碼呢?因爲我沒有看到或理解你的問題,這對我來說很好[np.take(a,a [3:7])'這是通過數組索引數組。 – ljetibo 2015-02-23 22:34:48

回答

2

按照numpy的文檔的把它做同樣的事情爲「花哨」的索引(索引陣列使用數組)。

的第二個參數np.take必須是陣列狀(陣列,列表,元組等),而不是一個對象slice。你可以構建一個索引數組或列表,做你想要的片斷:

a = np.arange(24).reshape(2, 3, 4) 

np.take(a, slice(1, 4, 2), 2) 
# TypeError: long() argument must be a string or a number, not 'slice' 

np.take(a, range(1, 4, 2), 2) 
# array([[[ 1, 3], 
#   [ 5, 7], 
#   [ 9, 11]], 

#  [[13, 15], 
#   [17, 19], 
#   [21, 23]]]) 

什麼是指數的最好方式使用切片以及僅在運行時知道的軸的陣列?

我最喜歡做的是使用np.rollaxis來使軸索引到第一個中,做我的索引,然後回滾到原來的位置。

例如,讓我們說,我想沿着第3軸的三維陣列的奇數編號的切片:

sliced1 = a[:, :, 1::2] 

如果我當時就想指定軸沿在運行時切片,我能做到這一點像這樣的:

n = 2 # axis to slice along 

sliced2 = np.rollaxis(np.rollaxis(a, n, 0)[1::2], 0, n + 1) 

assert np.all(sliced1 == sliced2) 

要解開一個班輪一點:

# roll the nth axis to the 0th position 
np.rollaxis(a, n, 0) 

# index odd-numbered slices along the 0th axis 
np.rollaxis(a, n, 0)[1::2] 

# roll the 0th axis back so that it lies before position n + 1 (note the '+ 1'!) 
np.rollaxis(np.rollaxis(a, n, 0)[1::2], 0, n + 1) 
+0

酷!感謝您分享'np.rollaxis'技巧! – user2561747 2015-02-27 22:41:06

2

我認爲你的意思是:

In [566]: np.take(A, slice(1,4)) 
... 
TypeError: int() argument must be a string or a number, not 'slice' 

作品就像喜歡np.insertnp.apply_along_axisA[1:4]

功能通過構建索引元組可以包括標量實現通用性,切片和數組。

ind = tuple([slice(1,4)]) # ndim terms to match array 
A[ind] 

np.tensordot是使用np.transpose移動動作軸到端(供np.dot)的一個例子。

另一個訣竅是將所有「過剩」軸倒塌爲一個重塑。然後重新塑形。

+0

使用'np.r_'是一個不錯的小巧解決方案。但是請記住用'A.shape [axis]'替換'None'來停止索引。並相應處理負面指標。 – user2561747 2015-02-27 23:08:17