简体   繁体   English

如何在不使用循环的情况下用列/行索引替换 (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?

I have a numpy array of 0's and 1's.我有一个 0 和 1 的 numpy 数组。

def random_array(p):
    return np.random.choice(2, 6, p=[p, 1-p])
my_matrix = np.array([random_array(j) for j in np.random.uniform(0.3, 1.0, 4)])

I can get indices of all num-zero elements as np.nonzero(my_matrix) .我可以将所有零零元素的索引作为np.nonzero(my_matrix) May you help me to allocate all these indices to the column number (even column indices will work, where we start from 0 rather 1) in which it is present.请您帮我将所有这些索引分配给它所在的列号(即使列索引也可以,我们从 0 而不是 1 开始)。 For example,例如,

array([[0, 2, 0, 4, 5, 6],
       [0, 0, 0, 4, 5, 0],
       [1, 2, 0, 4, 0, 0],
       [0, 2, 3, 4, 5, 6]])

Here, all 1's have been replaced with the column number.在这里,所有的 1 都被替换为列号。 Thus, this is for a matrix whose all non-zero elements were 1. If you can find the indices of column then that would also be fibulas because, I can get the same by adding 1.因此,这是一个所有非零元素都是 1 的矩阵。如果你能找到列的索引,那么它也将是 fibulas,因为我可以通过加 1 得到相同的结果。

Note: I do not wish to use any loop for this task.注意:我不希望为此任务使用任何循环。

You can multiply your array with another array of the same size containing the corresponding row/column index:您可以将数组与包含相应行/列索引的另一个相同大小的数组相乘:

## Dummy data
#  Array size
s = (6,4)
#  Axis along which we need to calculate the index:
a = 0
#  Random binary array
x = np.random.rand(*s).round()

#  Get the index along one axis using broadcasting (starting with 1)
x = x*(np.expand_dims(range(s[a]),len(s)-a-1)+1)

If I understand well, you want to replace all no zero elements with their column indices (starting from 1 instead of 0) right?如果我理解得很好,您想用它们的列索引(从 1 而不是 0 开始)替换所有非零元素,对吗? Then you can do it like:然后你可以这样做:

idx = np.nonzero(my_matrix)
my_matrix[idx[0], idx[1]] = idx[1]+1
In [169]: def random_array(p):
     ...:     return np.random.choice(2, 6, p=[p, 1-p])
     ...: my_matrix = np.array([random_array(j) for j in np.random.uniform(0.3, 1.0, 4)])
In [170]: my_matrix
Out[170]: 
array([[0, 0, 0, 0, 0, 0],
       [0, 1, 1, 0, 0, 0],
       [0, 0, 1, 1, 0, 1],
       [1, 1, 0, 0, 1, 0]])

Just multiply the range index.只需乘以范围索引。 By broadcasting (6,) arange is fine for columns:通过广播 (6,) arange 适用于列:

In [171]: np.arange(1,7)*my_matrix
Out[171]: 
array([[0, 0, 0, 0, 0, 0],
       [0, 2, 3, 0, 0, 0],
       [0, 0, 3, 4, 0, 6],
       [1, 2, 0, 0, 5, 0]])

for rows对于行

In [172]: np.arange(1,5)[:,None]*my_matrix
Out[172]: 
array([[0, 0, 0, 0, 0, 0],
       [0, 2, 2, 0, 0, 0],
       [0, 0, 3, 3, 0, 3],
       [4, 4, 0, 0, 4, 0]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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