[SciPy-user] Quick way to delete all 'values' from array

Scott Sinclair scott.sinclair.za@gmail....
Tue Jul 14 10:14:48 CDT 2009


>2009/7/14 Adrian Price-Whelan <adrian.prw@gmail.com>:
> I'm just looking for the quickest way to remove all X from an array
> [a,b,c,d,X,e,X,f,gX] or it could be multidimensional, I suppose, but
> thats the idea. I understand delete() will remove a value at a
> specific index, but I was unsuccessful in combining this function with
> 'where' to get what I want. Any suggestions?

If by 'quickest' you mean 'easiest'. Here's how to do it using fancy indexing:

>>> import numpy as np
>>> a = np.array([0, -1, 2, 3, -1, 4])
>>> a
array([ 0, -1,  2,  3, -1,  4])
>>> a = a[a != -1]
>>> a
array([0, 2, 3, 4])

This works because a != 1 returns a boolean array that can be used as
indices into the original array.

>>> a = np.array([0, -1, 2, 3, -1, 4])
>>> a != -1
array([ True, False,  True,  True, False,  True], dtype=bool)

See also:

http://docs.scipy.org/doc/numpy/user/basics.indexing.html

Cheers,
Scott


More information about the SciPy-user mailing list