Home > Software engineering >  Assign values to numpy array from list indices
Assign values to numpy array from list indices

Time:11-04

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

CodePudding user response:

This is simply indexing: b[a], given the second array is also numpy array.

Output:

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

CodePudding user response:

You just need to change the list to a numpy array as well, then it's simple indexing:

np.array(indices_list)[np_array]

does what you want, I think. Or not?

CodePudding user response:

Here's my iterative solution :

>>> 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)

Output :

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