Home > Software engineering >  Filtering a ndarray in numpy
Filtering a ndarray in numpy

Time:01-27

I have a ndarray and I want to filter out a particular value of it. My array is:

arr = np.array([
   [1., 6., 1.],
   [1., 7., 0.],
   [1., 8., 0.],
   [3., 5., 1.],
   [5., 1., 1.],
   [5., 2., 2.],
   [6., 1., 1.],
   [6., 2., 2.],
   [6., 7., 3.],
   [6., 8., 0.]
])

I want to filter out [6., 1., 1.]. So I have tried:

arr[arr != [6., 1., 1.]]

and I got:

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

which is not what I want (and also destroyed the previous structure of the array). I have also tried:

arr[arr[:] != [6., 1., 1.]]

but I got the same output as before.

P.S.: I know I can delete an element by its index, but I don't want to do that. I want to check for the particular element.

P.P.S.: For 1-d arrays my method works.

CodePudding user response:

You're very close. The boolean array you get tells you how many elements match in each row. You need to make sure that all the elements in a row match to delete it, or that any of the elements don't match to keep it:

arr[(arr != [6, 1, 1]).any(axis=1)]

You can also write it as

arr[~(arr == [6, 1, 1]).all(axis=1)]
  •  Tags:  
  • Related