0

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
2
  • 1
    The first fails because np_array is the set of indices; indices_list has the values. The second fails because lists can only be indexed with single values, not arrays. If indices_list is actually an array (or converted to one), the task is trivial. Commented Nov 3, 2021 at 15:21
  • I'm glad I could help. Would you mind accepting my answer, though? Commented Nov 4, 2021 at 18:43

3 Answers 3

2

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?

Sign up to request clarification or add additional context in comments.

1 Comment

You're welcome. Would you mind accepting my answer? Thx!
0

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

Output:

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.