2014-07-25 32 views
0

我不得不以下索引的集合使用ndarray.flatten()蟒若干陣列的陣列,Python的

ind = array([[array([0, 1, 3, 4])], 
      [array([0, 1, 2, 3, 4, 5])], 
      [array([1, 2, 4, 5])], 
      [array([0, 1, 3, 4, 6, 7])], 
      [array([0, 1, 2, 3, 4, 5, 6, 7, 8])], 
      [array([1, 2, 4, 5, 7, 8])], 
      [array([3, 4, 6, 7])], 
      [array([3, 4, 5, 6, 7, 8])], 
      [array([4, 5, 7, 8])]], dtype=object) 
一些數據的

讓說X;

X = array([[ 0. , 0. ], 
      [ 0.5, 0. ], 
      [ 1. , 0. ], 
      [ 0. , 0.5], 
      [ 0.5, 0.5], 
      [ 1. , 0.5], 
      [ 0. , 1. ], 
      [ 0.5, 1. ], 
      [ 1. , 1. ]]) 

有沒有一種方法,我可以替換以下for循環一些內置的功能在Python;

A_flat = ind.flatten()  
for i in range(N): 
    print X[i,0] - X[A_flat[i],0] 

> [ 0. -0.5 0. -0.5] 
    [ 0.5 0. -0.5 0.5 0. -0.5] 
    [ 0.5 0. 0.5 0. ] 
    [ 0. -0.5 0. -0.5 0. -0.5] 
    [ 0.5 0. -0.5 0.5 0. -0.5 0.5 0. -0.5] 
    [ 0.5 0. 0.5 0. 0.5 0. ] 
    [ 0. -0.5 0. -0.5] 
    [ 0.5 0. -0.5 0.5 0. -0.5] 
    [ 0.5 0. 0.5 0. ] 

並存儲結果到一個9×9零矩陣(或稀疏矩陣),以獲得讓說乙與正確索引;

+0

什麼是'N'繼續應該是? – chrisaycock

+0

@chrisaycock 'N = len(X [:,0])',這裏'N'是'9'。 – madf19

回答

0

由於問題描述,答案是否定的。

如果ind的列數相同,則答案爲肯定。

嘗試

import numpy as np 
ind = np.array([[4, 5, 6], 
       [0, 1, 2]]) 

print X[np.arange(len(ind))[:, np.newaxis], 0] - X[ind, 0] 

,看看你是否可以以任何方式,使ind陣列中的行和列均勻重新制定你的問題。如果這是不可能的,那麼循環在某種意義上將是不可避免的。

如果列上存在固定的上限,則可以嘗試使用蒙版數組。讓我們假設你想索引[[4, 5, 6], [0, 1]]。然後,你可以這樣寫

mask = np.array([[False, False, False], 
       [False, False, True]]) 

ind2 = np.ma.masked_where(mask, ind) # these are the indices that we would be interested in (we do not make use of this line later on) 

raw_output = X[np.arange(len(ind))[:, np.newaxis], 0] - X[ind, 0] 
masked_output = np.ma.masked_where(mask, raw_output) 

print masked_output 

爲了把它變成您指定的數據結構,那麼你可以用(可能不理想和更慢)列表理解

list_output = masked_output.tolist() 
final_output = [[num for num in arr if num is not None] for arr in list_output] 
+0

列數是未知的,但每列可以有的最大數量是N.行數總是N.這就是爲什麼我問是否有一種方法,我們可以通過'N將'ind'存儲到'N'中矩陣然後調用它。可能嗎?謝謝你的幫助。 – madf19

+0

你可以使用掩碼數組。讓我嘗試更新。 – eickenberg