[Numpy-discussion] Finding indices for all rows which contain nan (or anything else)

Robert Kern robert.kern at gmail.com
Thu Jul 13 14:56:11 CDT 2006


Webb Sprague wrote:
> Does anyone have some vectorized code that pulls out all the row
> indices for any row which has an nan (or a number less than 1 or
> whatever).  I want to subsequently be able to perform an operation
> with all the good rows.  See the imaginary code below.
> 
> a = numpy.array([[1,2],[nan,1], [2,3]])
> is_row_nan(a) == array([1])
> ii = numpy.negative(is_row_nan(a))
> 
> a[ii,:] # these are the ones I want.  Hopefully this is array([[1,2],[2,3]])
> 
> I can imagine doing this with a loop or with (maybe) some fancy set
> union stuff, but I am at a loss for vectorized versions.

(Untested)

def is_row_nan(a):
     return numpy.isnan(a).any(axis=-1)

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco





More information about the Numpy-discussion mailing list