Is there a numpy way to filter an array of arrays by a list of indices

Question:

Let’s say I have the numpy array x where x is

x = np.array(
  [
    [1, 2],
    [3, 4]
  ]
)

I also have a list of indices i where i = [0, 1]. I would like to get an array of the the value at index n[i] for every n in x.

The optimal output is

np.array([1, 4])

This can very obviously be done with a for loop, but I was wondering if there was a simpler *numpy* way to do it.

Asked By: Aayaan Sahu

||

Answers:

You can use indexing:

x[np.arange(x.shape[0]), i]

output: array([1, 4])

Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.