使用numpy.ndarray指定的数组替换元素的部分。

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

Replace elements of numpy.ndarray specified with ndarray

问题

我有一个2D的numpy.ndarray()和要替换的索引。

idx = np.array([[1, 0],
                [2, 1],
                [2, 3],])
array = np.array([[0, 0, 0, 0],
                  [0, 0, 0, 0],
                  [0, 0, 0, 0]]

我想要的结果如下所示的数组。

np.array([[0, 0, 0, 0],
          [1, 0, 0, 0],
          [0, 1, 0, 1]]

在数组中由idx指定的元素被替换为任意值。

英文:

I have 2D numpy.ndarray() and indices to be replaced.

idx = np.array([[1, 0],
                [2, 1],
                [2, 3],])
array = np.array([[0, 0, 0, 0],
                  [0, 0, 0, 0],
                  [0, 0, 0, 0]])

Which I want to have is like following array.

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

Elements where specified by idx in the array is replaced with an arbitrary value.

答案1

得分: 1

If I understand you correctly you want to index the array by 2D array idx:

array[idx[:, 0], idx[:, 1]] = 1
print(array)

Prints:

[[0 0 0 0]
 [1 0 0 0]
 [0 1 0 1]]
英文:

If I understand you correctly you want to index the array by 2D array idx:

array[idx[:, 0], idx[:, 1]] = 1
print(array)

Prints:

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

答案2

得分: 0

你可以通过循环遍历索引数组并手动设置每个指定索引处的值,或者直接像这样进行操作:array[idx[:, 0], idx[:, 1]] = 1

import numpy as np

idx = np.array([[1, 0],
                [2, 1],
                [2, 2]])

array = np.array([[0, 0, 0, 0],
                  [0, 0, 0, 0],
                  [0, 0, 0, 0]])
                  
array[idx[:, 0], idx[:, 1]] = 1
print(array)
英文:

You can do it either by looping on indices array and do manual set to value at each specified index or directly like this array[idx[:, 0], idx[:, 1]] = 1.

import numpy as np

idx = np.array([[1, 0],
                [2, 1],
                [2, 2]])

array = np.array([[0, 0, 0, 0],
                  [0, 0, 0, 0],
                  [0, 0, 0, 0]])
                  
array[idx[:, 0], idx[:, 1]] = 1
print(array)

huangapple
  • 本文由 发表于 2023年5月30日 07:27:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76360805.html
匿名

发表评论

匿名网友

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

确定