[英]How to replace values in numpy matrix columns with values from another array?
[英]How to replace all zeros in numpy matrix with corresponding values from another matrix
例如
a = np.matrix('1 0; 0 4')
b = mp.matrix('13 17;19 23')
通过执行我将获得的操作:
c = [[1 17]
[19 4]]
你可以使用np.where
:
c = np.where(a==0, b, a)
In [15]: c
Out[15]:
array([[ 1, 17],
[19, 4]])
使用逻辑索引:
d = (a==0)
a[d] = b[d]
d
是与a
或b
大小相同的真值数组,可用作掩码。 在赋值操作中仅考虑在d
中标记为True
的元素。 如果您需要一个包含结果的单独数组,
d = (a==0)
c = a.copy()
c[d] = b[d]
正如Anton所指出的,一个好方法是使用numpy.where()
:
c = numpy.where(a == 0, b, a)
请注意,这几乎等同于上面的三行版本,因为表达式a == 0
实际上创建了一个像d
一样的掩码数组,然后将其传递到where
。
两种方法都有优点和缺点。 如果你在原地进行转换(例如在矩阵中固定零),第一个选项是最好的。 如果你只进行一次计算,Anton的方法是最好的。 如果你要使用相同的掩膜很多次,这是更好地面具从计算的应用程序分开where
:
d = (a == 0)
c = numpy.where(d, a, b)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.