簡體   English   中英

如何在numpy數組的每一行中將第n個非零元素更改為零

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

我有一個寬的二進制二維 numpy 數組,如下所示:

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

每行有 8 個非零元素。 我想用零快速替換每行中的第 n 個非零元素(最終每行有 7 個非零元素)。

有沒有一種簡單的方法可以在沒有循環的情況下快速執行此替換?

您可以找到不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

您可以獲取非零元素的索引並使用它們來替換數組中的值

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