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

Scott Sinclair scott.sinclair.za at gmail.com
Tue Jul 14 11:14:48 EDT 2009


>2009/7/14 Adrian Price-Whelan <adrian.prw at 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