Home > Software engineering >  np keep rows contain specific value python
np keep rows contain specific value python

Time:04-06

I have 2D np array, how can I keep only rows contain specific value, than flatten the array and keep only unique values.

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

if I need to keep only rows contain 2. I expect the result ([0,2,4])

CodePudding user response:

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