[Numpy-discussion] Help with np.where and datetime functions
Neil Crighton
neilcrighton at gmail.com
Wed Jul 8 12:30:31 EDT 2009
John [H2O] <washakie <at> gmail.com> writes:
> What I am trying to do (obviously?) is find all the values of X that fall
> within a time range.
>
> Specifically, one point I do not understand is why the following two methods
> fail:
>
> --> 196 ind = np.where( (t1 < Y[:,0] < t2) ) #same result
> with/without inner parens
> TypeError: can't compare datetime.datetime to numpy.ndarray
>
> OR trying the 'and' method:
>
> --> 196 ind = np.where( (Y[:,0]>t1) and (Y[:,0]<t2) )
> ValueError: The truth value of an array with more than one element is
> ambiguous. Use a.any() or a.all()
>
Use (t1 < Y[:,0]) & (Y[:,0] < t2). The python keywords 'and' and 'or' can't
be overloaded, but the bitwise operators can be (and are) overloaded by arrays.
Conditionals like a < x < b are converted to (a < x) and (x < b), which is why
they don't work either. There is a proposal to enable overloadable 'and' and
'or' methods (http://www.python.org/dev/peps/pep-0335/), but I don't think it's
ever got enough support to be accepted.
Also, if you don't need the indices, you can just use the conditional
expression as a boolean mask:
>>> condition = (t1 < Y[:,0]) & (Y[:,0] < t2)
>>> Y[:,0][condition]
Neil
More information about the NumPy-Discussion
mailing list