从列表索引中为 numpy 数组赋值

Assign values to numpy array from list indices

我有一个 numpy 数组和一个列表,比如:

np_array = np.random.randint(0,3,(2,3))
np_array
array([[1, 1, 2],
       [2, 1, 2]])

indices_list:
[7,8,9]

并希望有一个 numpy 数组,它从列表的索引中获取值(即,如果 np_array 的值为 2,则将 indices_list[2] 设置为新数组的值):

np_array_expected
array([[8, 8, 9],
       [9, 8, 9]])

我做了这个不成功的尝试:

np_array[indices_list]
Traceback (most recent call last):

  File "/tmp/ipykernel_27887/728354097.py", line 1, in <module>
    np_array[indices_list]

IndexError: index 7 is out of bounds for axis 0 with size 2


indices_list[np_array]
Traceback (most recent call last):

  File "/tmp/ipykernel_27887/265649000.py", line 1, in <module>
    indices_list[np_array]

TypeError: only integer scalar arrays can be converted to a scalar index

这只是索引:b[a],因为第二个数组也是 numpy 数组。

输出:

array([[8, 8, 9],
       [9, 8, 9]])

你只需要将列表也更改为一个numpy数组,然后它是简单的索引:

np.array(indices_list)[np_array]

做你想做的,我想。还是不行?

这是我的迭代解决方案:

>>> arr = np.array([[1,1,2],[2,1,2]])
>>> indices_list = [7,8,9]
>>> for i in range(arr.shape[0]) :
...     for j in range(arr.shape[1]) :
...         arr[i][j] = indices_list[arr[i][j]]

>>> print(arr)

输出:

array([[8, 8, 9],
       [9, 8, 9]])