简体   繁体   中英

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:

output = (a > 0) * b

Another way would be:

a[a>0] = np.tile(b,(a.shape[0],1))[a>0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM