Home > OS >  Find and slice by indices in 2D numpy array where according to value in certain index of each array?
Find and slice by indices in 2D numpy array where according to value in certain index of each array?

Time:03-19

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.

CodePudding user response:

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]
  • Related