简体   繁体   中英

Delete some array elements from numpy array

I have the numpy array:

a = np.array([[ 255,255,255],
              [ 255,2,255],
              [ 3,123,23],
              [ 255,255,255],
              [ 0, 255, 3]])

And I want to delete all the elements with [ 255,255,255], the result should be:

[[ 255,2,255],
 [ 3,123,23],
 [ 0, 255, 3]])

I tried with:

import numpy as np
a = np.array([[ 255,255,255],
              [ 255,2,255],
              [ 3,123,23],
              [ 255,255,255],
              [ 0, 255, 3]])

np.delete(a, [255,255,255])

but nothing happens.

You can do this:

np.array([x for x in a if np.any(x != 255)])

which gives:

array([[255,   2, 255],
       [  3, 123,  23],
       [  0, 255,   3]])

Edit: To avoid list comprehensions -

np.delete(a, np.where((a == 255).all(axis=1)), axis=0)

here is a fast vectorized way to do it

a[(a!=255).any(axis=1),:]
Out[136]: 
array([[255,   2, 255],
       [  3, 123,  23],
       [  0, 255,   3]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM