将数组中除第一个1之外的所有元素替换为0。

huangapple go评论64阅读模式
英文:

Replace all but the first 1 in an array with 0

问题

我正在尝试找到一种方法,将所有重复的1替换为0。例如:

[[0,1,0,1,0],
[1,0,0,1,0],
[1,1,1,0,1]]

应该变成:

[[0,1,0,0,0],
[1,0,0,0,0],
[1,0,0,0,0]]

我找到了一个类似的问题,但是解决方案似乎不起作用。你可以查看这个链接:https://stackoverflow.com/questions/37909364/numpy-setting-duplicate-values-in-a-row-to-0

英文:

I am trying to find a way to replace all of the duplicate 1 with 0. As an example:

[[0,1,0,1,0],
[1,0,0,1,0],
[1,1,1,0,1]]

Should become:

[[0,1,0,0,0],
[1,0,0,0,0],
[1,0,0,0,0]]

I found a similar problem, however the solution does not seem to work https://stackoverflow.com/questions/37909364/numpy-setting-duplicate-values-in-a-row-to-0

答案1

得分: 3

假设数组只包含零和一,您可以使用 numpy.argmax 找到每行的最大值,然后使用高级索引将索引处的值重新分配到一个零数组上。

arr = np.array([[0,1,0,1,0],
[1,0,0,1,0],
[1,1,1,0,1]])

res = np.zeros_like(arr)
idx = (np.arange(len(res)), np.argmax(arr, axis=1))
res[idx] = arr[idx]

res
array([[0, 1, 0, 0, 0],
       [1, 0, 0, 0, 0],
       [1, 0, 0, 0, 0]])
英文:

Assume array contains only zeros and ones, you can find the max value per row using numpy.argmax and then use advanced indexing to reassign the values on the index to a zeros array.

arr = np.array([[0,1,0,1,0],
[1,0,0,1,0],
[1,1,1,0,1]])

res = np.zeros_like(arr)
idx = (np.arange(len(res)), np.argmax(arr, axis=1))
res[idx] = arr[idx]

res
array([[0, 1, 0, 0, 0],
       [1, 0, 0, 0, 0],
       [1, 0, 0, 0, 0]])

答案2

得分: 2

尝试循环遍历网格的每一行

在每一行中,找到所有的1。特别是要找到它们的索引(在行内的位置)。你可以使用列表推导和enumerate来做到这一点,它会自动为每个元素提供一个索引。

然后,在同一行内,遍历除了第一个1以外的每个1,将它们设置为零。

grid = [[0, 1, 0, 1, 0], [1, 0, 0, 1, 0], [1, 1, 1, 0, 1]]

for row in grid:
    ones = [i for i, element in enumerate(row) if element == 1]
    for i in ones[1:]:
        row[i] = 0

print(grid)

结果为:[[0, 1, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]]

英文:

Try looping through each row of the grid

In each row, find all the 1s. In particular you want their indices (positions within the row). You can do this with a list comprehension and enumerate, which automatically gives an index for each element.

Then, still within that row, go through every 1 except for the first, and set it to zero.

grid = [[0, 1, 0, 1, 0], [1, 0, 0, 1, 0], [1, 1, 1, 0, 1]]

for row in grid:
    ones = [i for i, element in enumerate(row) if element==1]
    for i in ones[1:]:
        row[i] = 0

print(grid)

Gives: [[0, 1, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]]

答案3

得分: 0

你可以使用cumsum:

(arr.cumsum(axis=1).cumsum(axis=1) == 1) * 1

这将创建一个累积和,然后通过检查值是否为1,您可以找到第一个1。

英文:

You can use cumsum:

(arr.cumsum(axis=1).cumsum(axis=1) == 1) * 1

this will create a cummulative sum, by then checking if a value is 1 you can find the first 1s

huangapple
  • 本文由 发表于 2023年2月6日 06:25:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75355928.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定