I have a numpy array and a list, say:
np_array = np.random.randint(0,3,(2,3))
np_array
array([[1, 1, 2],
[2, 1, 2]])
indices_list:
[7,8,9]
and would like to have a numpy array which takes its values from the indices of the list (i.e., if np_array has value 2, set indices_list[2] as value on new array):
np_array_expected
array([[8, 8, 9],
[9, 8, 9]])
I did this unsuccessful attempt:
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_arrayis the set of indices;indices_listhas the values. The second fails because lists can only be indexed with single values, not arrays. Ifindices_listis actually an array (or converted to one), the task is trivial.