[Numpy-discussion] FW: numpy array matching

Chris Barker cbarker at jps.net
Wed Mar 14 12:02:07 CST 2001


"Paul F. Dubois" wrote: 
> -------------------------------------------
> If I have a character array t:
> 
> >>> t = array(['abcd','aacd','ddfa','qqcd'])
> >>> print t
> [[a b c d]
>  [a a c d]
>  [d d f a]
>  [q q c d]]
> 
> I'm trying to find the row numbers that
> have a 'c' in the third column
> (and I'm trying to avoid a 'for' loop).
> 
> What's the most efficient way to
> create an array that contains the indexes
> of the rows that match a particular pattern?
> (using masks?)
> 
> The answer should be an array ([0,1,3])

> The obvious approach using equal doesn't seem to work. I'll forward your
> request.

It seems that equal() does not support the char type (anyone know why
not?):

>>> equal(t,'c')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: function not supported for these types, and can't coerce to
supported types

The following is kind of an ugly kludge, but it does work:

>>> from Numeric import *

>>> t = array(['abcd','aacd','ddfa','qqcd'])

>>> t2 = t.astype(UnsignedInt8)

>>> nonzero(equal(t2,ord('c'))[:,2])

array([0, 1, 3])


-Chris

-- 
Christopher Barker,
Ph.D.                                                           
cbarker at jps.net                      ---           ---           ---
http://www.jps.net/cbarker          -----@@       -----@@       -----@@
                                   ------@@@     ------@@@     ------@@@
Water Resources Engineering       ------   @    ------   @   ------   @
Coastal and Fluvial Hydrodynamics -------      ---------     --------    
------------------------------------------------------------------------
------------------------------------------------------------------------




More information about the Numpy-discussion mailing list