[英]How to assign all non-zero elements in each numpy column to a value in an array whose size is the same as the number of columns?
So that's a bit of a mouthful.所以这有点拗口。 But here's what I'm looking to do:
但这是我想要做的:
b = np.array([7,8,2,3])
a = np.array([[1, 1, 0, 1],
[0, 0, 1, 1],
[0, 1, 1, 0]])
*** The Magic Happens ***
array([[7, 8, 0, 3],
[0, 0, 2, 3],
[0, 8, 2, 0]])
I hardly think there is a faster/neater answer for this.我几乎不认为有一个更快/更整洁的答案。 Writing for others to find it helpful.
为其他人写作以发现它有帮助。 As @Mark mentioned in the comments, you can find non-zero elements by
a>0
and multiplying it into b
will broadcast b
to a
's shape by repeating rows and multiply element-wise:正如评论中提到的@Mark,您可以通过
a>0
找到非零元素,并将其乘以b
将通过重复行并将元素相乘来广播b
到a
的形状:
output = (a > 0) * b
Another way would be:另一种方法是:
a[a>0] = np.tile(b,(a.shape[0],1))[a>0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.