np keep rows contain specific value python

Viewed 112

I have a 2D numpy array, how can I keep only rows that contain a specific value, and then flatten the array keeping only unique values.

array([[0, 2],
       [1, 3],
       [2, 4],
       [3, 5],
       [4, 6],
       [5, 7]])

If I need to keep only rows containing 2, I expect the result ([0,2,4])

1 Answers

IIUC, you could use:

np.unique(a[(a==2).any(1)].ravel())

output: array([0, 2, 4])

using pandas

this is both faster and not sorting the data

import pandas as pd
pd.unique(a[(a==2).any(1)].ravel())

output: array([0, 2, 4])

credit to @MichaelSzczesny

Related