2012-07-30 45 views
2

我有兩個數組索引和我要回所有的指標之間,就像一個切片功能,手動將是這樣的:功能切片指數在numpy的

ind1 = np.array([2,6]) 
ind2 = np.array([2,3]) 

final = np.array([[2,2,2], [4,5,6]]) 

由於軸沿至片是不固定的,我想出了這個:

def index_slice(ind1,ind2): 
    return np.indices(1 + ind1 - ind2) + ind2[:,np.newaxis,np.newaxis] 

final = index_slice(ind1,ind2) 

然而,這依賴於1 + ind1 > ind2,它包括最後一個索引,以及(不符合Python)。有誰會知道這樣做的功能,還是更清潔的實現?
預先感謝您。 Diego

P.S.給出一些這個想法來自何處的背景。我正在考慮一個矩陣的子矩陣,我想從兩個角落的索引中訪問它們。由於問題的性質,給定的角落並不總是具有相同的方向,你可以在@Pelson的答案中看到。

+0

因此對於'ind1'和'ind2'的每個成員,你想要一個包含插入索引的'final'中的行嗎? 'ind1'和'ind2'是否總是兩個值?另外,就像phihag說的那樣,如果你接受以前的問題的答案,它會鼓勵人們回答你未來的問題。 – 2012-07-30 21:34:50

+0

謝謝你的提示。當我試圖添加一些評論時,我並沒有意識到要標記正確的答案,所以是的...這樣好多了。 – Diego 2012-07-31 02:41:36

+0

當我想到'ind1'和'ind2'時,它們可以是任何ND數組中的兩個索引,'final'應該填充它們之間的矩陣......就像在pelson的答案中一樣。 – Diego 2012-07-31 02:47:15

回答

0

我沒有它的一個眼線,但像下面這樣將重現你似乎結果被要求:

def index_slice(arr1, arr2): 
    lens = np.abs(arr1 - arr2) 
    if not all((lens == max(lens)) | (lens == 0)): 
     raise ValueError('The number of indices in some dimensions were inconsistent. Array lengths were %r' % lens) 

    max_len = lens.max() 
    result = np.empty((len(lens), max_len), dtype=np.int32) 

    for dim, (a, b) in enumerate(zip(arr1, arr2)): 
     if a == b: 
      result[dim, :] = a 
     elif a > b: 
      result[dim, :] = np.arange(a, b, -1) 
     else: 
      result[dim, :] = np.arange(a, b) 

    return result 

例如:

>>> ind1 = np.array([2, 6]) 
>>> ind2 = np.array([2, 3]) 
>>> print index_slice(ind1, ind2) 
[[2 2 2] 
[6 5 4]] 


>>> ind1 = np.array([2, 6, 1]) 
>>> ind2 = np.array([2, 3, 4]) 
>>> print index_slice(ind1, ind2) 
[[2 2 2] 
[6 5 4] 
[1 2 3]] 

然而,問這個問題引起了我的懷疑,即如果你想分享你的上游邏輯,你可能正在做一些可以以更簡單的方式完成的事情。

HTH

+0

這正是我正在尋找的。感謝您的反饋。 – Diego 2012-07-31 03:02:05