2016-03-01 28 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组合索引数组与切片。

相关问题