【发布时间】:2021-12-17 22:51:05
【问题描述】:
我有一个 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
【问题讨论】:
-
第一个失败,因为
np_array是索引集;indices_list具有值。第二个失败,因为列表只能用单个值而不是数组来索引。如果indices_list实际上是一个数组(或转换为一个数组),那么任务就很简单了。 -
很高兴能帮上忙。不过,您介意接受我的回答吗?