[Numpy-discussion] Nonzero behaving strangely?
Christopher Barker
Chris.Barker at noaa.gov
Thu Mar 17 18:31:18 EDT 2011
On 3/17/11 3:17 PM, santhu kumar wrote:
> nid = (res[:,4]==2).nonzero()
> nid tuple turns out to be empty. But the very first row satisfies the
> criteria.
it works for me:
In [45]: arr
Out[45]:
array([[ 33.35053669, 49.4615004 , 44.27631299, 1. , 2.
],
[ 32.84263059, 50.24752036, 43.92291659, 1. , 0.
],
[ 33.68999668, 48.90554673, 43.51746687, 1. , 0.
],
[ 34.11564931, 49.77487763, 44.83843076, 1. , 0.
],
[ 32.4641859 , 48.65469145, 45.09300791, 1. , 3.
],
[ 32.15428526, 49.26922262, 45.92959026, 1. , 0.
],
[ 31.23860825, 48.21824628, 44.30816331, 1. , 0.
],
[ 30.71171138, 47.45600573, 44.9282456 , 1. , 0.
],
[ 30.53843426, 49.07713258, 44.20899822, 1. , 0.
],
[ 31.54722284, 47.61953925, 42.95235178, 1. , 0.
],
[ 32.44334635, 48.10500653, 42.51103537, 1. , 0.
],
[ 31.77269609, 46.53603145, 43.06468455, 1. , 0.
],
[ 30.1820843 , 47.80819604, 41.77667819, 1. , 0.
],
[ 30.78652668, 46.82907769, 40.38586451, 1. , 0.
],
[ 30.05963091, 46.84268609, 39.54583693, 1. , 0.
],
[ 31.75239177, 47.22768463, 40.00717713, 1. , 0.
],
[ 30.94617127, 45.76986265, 40.68226643, 1. , 0.
],
[ 33.20069679, 47.42127403, 45.66738249, 1. , 0.
],
[ 34.39608116, 47.25481126, 45.4438599 , 1. , 0.
]])
In [46]: arr.shape
Out[46]: (19, 5)
In [47]: nid = (arr[:,4]==2).nonzero()
In [48]: nid
Out[48]: (array([0]),)
Maybe you are having a floating point comparison problem -- i.e.e that
"2.0" is really "1.9999999999" or something.
Checking equality with floating point numbers is fraught with problems.
Also, y9ou amy not need teh nonzero:
In [56]: arr[:,4]==2
Out[56]:
array([ True, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False,
False], dtype=bool)
that's a boolean array that can be used for indexing, operating with
"where", etc.
HTH,
-Chris
--
Christopher Barker, Ph.D.
Oceanographer
Emergency Response Division
NOAA/NOS/OR&R (206) 526-6959 voice
7600 Sand Point Way NE (206) 526-6329 fax
Seattle, WA 98115 (206) 526-6317 main reception
Chris.Barker at noaa.gov
More information about the NumPy-Discussion
mailing list