英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论