[SOLVED] Find and slice by indices in 2D numpy array where according to value in certain index of each array?

Issue

I have many 2D numpy arrays that look like this:

arr = np.array([[2,2],
                [2,3],
                [3,4],
                [3,5],
                [3,6],
                [4,7]))

How can I query the 2D array and retrieve all the arrays with a value of, for example, 3 in the 0 index? So I would want:

[[3,4],[3,5],[3,6]]

I considered turning it into a list of lists, but that seems inefficient as I have a lot of queries to make. Using np.argwhere or np.where doesn’t seem to isolate by index value, either.

Thank you.

Solution

For advanced indexing, at first we must find elements which have the specified number as its first argument by arr[:, 0] == 3, so:

arr[arr[:, 0] == 3]

Answered By – Ali_Sh

Answer Checked By – Mary Flores (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *