2

I have an unknown 2D numpy array like the following:

a = np.array([
 [1, 2],
 [0, 2],
])

I want to use the elements of the array as an index to another array b to produce the following effect:

b = np.random.randn(5, 5)
c = b[[1, 2], [0, 2]]

How can I use the variable a to replace the hardcoded values in the index?

Using the following code did not work:

b = np.random.randn(5, 5)
c = [*a]

As the * expression is used in an index.

Ivan
41.2k9 gold badges78 silver badges119 bronze badges
asked Sep 6, 2021 at 19:23
2
  • Is the number of rows on a always equal to 2? Commented Sep 6, 2021 at 19:28
  • no it is a 2D array where the size is not known when writing the program Commented Sep 6, 2021 at 19:29

2 Answers 2

4

Just change the outer layer of a to a tuple to trigger advanced indexing: b[tuple(a)].

This is pretty much how the index syntax of b[[1, 2], [0, 2]] is interpreted; the elements are changed to NumPy arrays and are put into a tuple.

answered Sep 6, 2021 at 19:29
Sign up to request clarification or add additional context in comments.

Comments

2

I don't know if I got it but, try using a list for the index instead of an np array:

import numpy as np
a = [
 [1, 2],
 [0, 2]
 ]
b = np.random.randn(5, 5)
c = b[a]
answered Sep 6, 2021 at 19:33

1 Comment

This will work for now, but NumPy is planning to change the default treatment of non-tuples arr[tuple(not_a_tuple)] to arr[np.array(not_a_tuple)], which does something different. This code currently prints a FutureWarning that suggests you write arr[tuple(not_a_tuple)] for future versions.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.