2013-12-23 38 views
1

好it's晚了,我不能再解決最簡單的問題:替換「零柱」與值從numpy的陣列

我有「零列」的矩陣,這些列應改爲

從另一陣列(同一列的索引),具有相同的列數的值:

a=np.array([[2,0,0,0],[1,0,2,0],[1,0,5,0]]) 
b=np.array([0.3,0.4,0.6,0.8]) 

結果應該是:

c=np.array([[2,0.4,0,0.8],[1,0.4,2,0.8],[1,0.4,5,0.8]]) 

我想:

#searches for an entire zero-column indexes 
wildcard_cols = np.nonzero(a.sum(axis=0) == 0) 

我得到:

out: wildcard_cols=array([[1, 3]], dtype=int64)# that is right 

的話,我想從這個輸出獲取列表遍歷列表中的項目

wildcard_cols=np.asarray(wildcard_cols) 
wildcard_cols=wildcard_cols.tolist()  

,但我得到列表中的列表(?) out = [[1,3]]

所以我不能做:

for item in wildcard_cols: 
    a[:,item]=b[item] 
    #this does not work because i want to change every value in the column 

我想也許複雜的,但也許有人找到一個快速的解決方案......

+1

爲什麼你用'0.3'和'0.8'填充?如果它們對齊,它會不會是「0.4」和「0.8」? – DSM

+0

你是對的,我編輯了問題 – Hiatus

回答

2

IIUC,怎麼樣:

>>> a = np.array([[2,0,0,0],[1,0,2,0],[1,0,5,0]])*1.0 
>>> b = np.array([0.3,0.4,0.6,0.8]) 
>>> wild = (a == 0).all(axis=0) 
>>> c = a.copy() 
>>> c[:,wild] = b[wild] 
>>> c 
array([[ 2. , 0.4, 0. , 0.8], 
     [ 1. , 0.4, 2. , 0.8], 
     [ 1. , 0.4, 5. , 0.8]]) 
+0

謝謝,爲什麼你乘以'* 1.0' – Hiatus

+0

因爲如果你不這樣做,'a'會有'dtype = int'。如果你試圖將一個float放入一個int數組中,你將不會得到你想要的。 – DSM

+0

但是,檢查浮點數上的相等性是否正確? –

0

短一點,並與高維數組作爲工作只要它們是可以播放的

np.where((a == 0.).all(axis=0), b, a) 

不幸的是,因爲numpy 1.8它的速度比直接慢像DSM提出的索引,更普遍的變體將是:

wild = (a == 0).all(axis=0) 
c = a.copy() 
c[(slice(None),) + np.nonzero(wild)] = b[wild]