简体   繁体   English

如何在numpy数组的每一行中将第n个非零元素更改为零

[英]How change nth non-zero element to zero in each row in numpy array

I have a wide, binary, 2-d numpy array as follows:我有一个宽的二进制二维 numpy 数组,如下所示:

np_var:
0, 0, 1, 0, 1, ..., 0, 1
1, 0, 1, 0, 0, ..., 1, 0
...

Each row has 8 non-zero elements.每行有 8 个非零元素。 I would like to quickly replace the nth non-zero element in each row with a zero (to end up with 7 non-zero elements per row).我想用零快速替换每行中的第 n 个非零元素(最终每行有 7 个非零元素)。

Is there a numpy way to perform this replacement quickly without a loop?有没有一种简单的方法可以在没有循环的情况下快速执行此替换?

You can find where you don't have zero then create a replacement array base all non_zero + one_zero and do replace like below: (I write small example with three non zero and replace the third nonzero with zero)您可以找到不zero的位置,然后创建一个替换array ,以所有non_zero + one_zero ,并进行如下替换:(我用three non zero编写小示例,并将第三个非零替换为零)

row = 5
non_zero = 3
# creating sample array
arr = np.concatenate((np.zeros((row,2)), np.ones((row,non_zero))), axis=1)
print(np.count_nonzero(arr))
#15

# creating replace array
rep = np.array(([1]*(non_zero-1)+[0])*row)
# suffle array
[np.random.shuffle(x) for x in arr]
print(arr)
# [[0. 0. 1. 1. 1.]
#               ^^ thrid nonzero
#  [1. 0. 1. 0. 1.]
#               ^^ thrid nonzero
#  [0. 1. 0. 1. 1.]
#               ^^ thrid nonzero
#  [1. 0. 1. 1. 0.]
#            ^^ thrid nonzero
#  [0. 1. 1. 1. 0.]]
#            ^^ thrid nonzero

arr[np.where(arr!=0)] = rep
print(np.count_nonzero(arr))
# 10

print(arr)
# [[0. 0. 1. 1. 0.]
#               ^^ thrid nonzero to zero
#  [1. 0. 1. 0. 0.]
#               ^^ thrid nonzero to zero
#  [0. 1. 0. 1. 0.]
#               ^^ thrid nonzero to zero
#  [1. 0. 1. 0. 0.]
#           ^^ thrid nonzero to zero
#  [0. 1. 1. 0. 0.]]
#           ^^ thrid nonzero to zero

You can get the indices of non zero elements and use them to replace the values in the array您可以获取非零元素的索引并使用它们来替换数组中的值

arr = np.array(...)
print(arr)

# [[1 1 1 0 0 1 0 1 1 0 0 1 1 0]
#  [0 1 1 1 1 0 1 0 0 1 1 0 1 0]
#  [1 0 1 1 0 1 1 1 0 1 0 0 1 0]
#  [0 1 1 0 1 0 0 1 1 1 1 0 1 0]
#  [1 1 1 0 0 1 1 0 0 1 1 0 0 1]
#  [0 0 1 1 1 1 1 0 1 1 0 0 1 0]
#  [1 0 1 0 1 0 1 1 1 0 0 1 0 1]
#  [1 0 1 1 1 0 1 1 0 0 1 0 1 0]
#  [0 0 1 1 1 1 0 1 0 1 1 0 0 1]
#  [0 1 1 1 0 0 0 1 1 0 1 1 1 0]]

nth_element = 5
non_zero_count = int(np.count_nonzero(arr) / len(arr)) # can be replaced by 8 if the size is fixed
indices = arr.nonzero()[1][nth_element - 1::non_zero_count]
arr[np.arange(len(arr)), indices] = 5
print(arr)

# [[1 1 1 0 0 1 0 5 1 0 0 1 1 0]
#  [0 1 1 1 1 0 5 0 0 1 1 0 1 0]
#  [1 0 1 1 0 1 5 1 0 1 0 0 1 0]
#  [0 1 1 0 1 0 0 1 5 1 1 0 1 0]
#  [1 1 1 0 0 1 5 0 0 1 1 0 0 1]
#  [0 0 1 1 1 1 5 0 1 1 0 0 1 0]
#  [1 0 1 0 1 0 1 5 1 0 0 1 0 1]
#  [1 0 1 1 1 0 5 1 0 0 1 0 1 0]
#  [0 0 1 1 1 1 0 5 0 1 1 0 0 1]
#  [0 1 1 1 0 0 0 1 5 0 1 1 1 0]]

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

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