1

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])

Daniel F
  • 13,620
  • 2
  • 29
  • 55
user18628648
  • 101
  • 5

1 Answers1

1

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

mozway
  • 194,879
  • 13
  • 39
  • 75