2

I have a 2-D array that looks like this:

my_array = np.array([[1,7]
                     [2,4]
                     [3,10] 
                     [4,3] 
                     [5,23]])

and I have an index array which looks like this:

index_array = np.array([0,2,3])

as an output I want to get a matrix containing only the rows from the index array so the shape of the output matrix should be (3,2) and it should look like this:

[[1,7]
 [3,10]
 [4,3]]

The solution shouldn't use a for loop and should work with any 2-D matrix. Thanks in advance :)

1

2 Answers 2

3

you can use numpy array slicing notation to select your rows :D

import numpy as np

my_array = np.array([[1,7],
                     [2,4],
                     [3,10], 
                     [4,3],
                     [5,23]])

print(my_array[[0,2,3]])

my_array[index_array] would work as well

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

Comments

0

not sure if a list comprehension qualifies as a for loop, but you can have this one-line solution:

[list(my_array[i]) for i in index_array]

that will return [[1, 7], [3, 10], [4, 3]].

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.