简体   繁体   English

如何将每个 numpy 列中的所有非零元素分配给大小与列数相同的数组中的值?

[英]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将通过重复行并将元素相乘来广播ba的形状:

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.

相关问题 计算2D NumPy数组中每行和每列内的非零元素 - Counting non-zero elements within each row and within each column of a 2D NumPy array 改组数组中每一行的非零元素-Python / NumPy - Shuffling non-zero elements of each row in an array - Python / NumPy NumPy - 在 nd 数组的每一列中查找和打印非零元素 - NumPy - Finding and printing non-zero elements in each column of a n-d array 用相同的值在非零元素之间的numpy数组中填充零 - Filling zeros in numpy array that are between non-zero elements with the same value 如何在不使用循环的情况下用列/行索引替换 (0,1) numpy 数组的非零元素? - How to replace non-zero elements of a (0,1) numpy array by it's column/ row indices without using a loop? 如何将python列表或numpy数组中的所有非零元素移到一侧? - how to move all non-zero elements in a python list or numpy array to one side? 如何获取NumPy掩码数组的最后一个非零值? - How to get the last non-zero value of NumPy masked array? 如何快速获取numpy数组中非零值的索引? - How to get the index of non-zero value in a numpy array quickly? 如何在numpy数组的每一列中找到第一个非零值? - How to find first non-zero value in every column of a numpy array? 如何在numpy数组的每一行中将第n个非零元素更改为零 - How change nth non-zero element to zero in each row in numpy array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM