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

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

Replace elements of numpy.ndarray specified with ndarray

问题

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

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

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

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

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

英文:

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

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

Which I want to have is like following array.

  1. np.array([[0, 0, 0, 0],
  2. [1, 0, 0, 0],
  3. [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:

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

Prints:

  1. [[0 0 0 0]
  2. [1 0 0 0]
  3. [0 1 0 1]]
英文:

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

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

Prints:

  1. [[0 0 0 0]
  2. [1 0 0 0]
  3. [0 1 0 1]]

答案2

得分: 0

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

  1. import numpy as np
  2. idx = np.array([[1, 0],
  3. [2, 1],
  4. [2, 2]])
  5. array = np.array([[0, 0, 0, 0],
  6. [0, 0, 0, 0],
  7. [0, 0, 0, 0]])
  8. array[idx[:, 0], idx[:, 1]] = 1
  9. 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.

  1. import numpy as np
  2. idx = np.array([[1, 0],
  3. [2, 1],
  4. [2, 2]])
  5. array = np.array([[0, 0, 0, 0],
  6. [0, 0, 0, 0],
  7. [0, 0, 0, 0]])
  8. array[idx[:, 0], idx[:, 1]] = 1
  9. 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:

确定