首页 > 解决方案 > 从列表索引为 numpy 数组赋值

问题描述

我有一个 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

标签: pythonlistnumpyindices

解决方案


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

输出:

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

推荐阅读