2016-03-01 16 views
3

我有一個m X 3矩陣和長度爲m的陣列過濾的柱. 我想要做以下如何設置一個值,以元件在由另一個陣列

a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]]) 
b = np.array([1, 2, 1, 3, 3]) 
me = np.mean(a[np.where(b==1)][:, 0]) 
a[np.where(b==1)][:, 0] = me 

問題是

a[np.where(b==1)][:, 0] 

返回[1, 7]而不是[4, 4]

回答

2

您正在將索引數組與切片相結合: [np.where(b==1)]是索引數組,[:, 0]是切片。你做這個拷貝的方式會被返回,因此你可以在拷貝上設置新的值。你應該做:

a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]]) 
b = np.array([1, 2, 1, 3, 3]) 
me = np.mean(a[np.where(b==1)][:, 0]) 
a[np.where(b==1), 0] = me 

另見https://docs.scipy.org/doc/numpy/user/basics.indexing.html組合索引數組與切片。

相關問題