Issue
Python support chaining comparison:
1<2<3<4
How to do that for NumPy?
If only 3 array, we can do this:
a = np.array([1,2,4,5,6])
b = np.array([2,6,1,5,6])
c = np.array([7,4,6,6,8])
np.logical_and((a <= b),(b <= c))
With 4 array, it becomes too burdensome since np.logical_and
only accept 2 inputs.
a = np.array([1,2,4,5,6])
b = np.array([2,6,1,5,6])
c = np.array([7,4,6,6,8])
d = np.array([8,9,9,9,2])
np.logical_and((a <= b),(b <= c)) # work
np.logical_and((b <= c),(c <= d)) # work
np.logical_and((a <= b),(b <= c),(c <= d)) # not work
Edit: Slightly add complexity, on 2D:
a = np.array([[1,2,3],
[4,5,6]])
b = np.array([[2,6,3],
[1,5,6]])
c = np.array([[7,4,3],
[6,6,8]])
d = np.array([[8,9,3],
[9,9,2]])
Solution
Simply use &
:
(a <= b) & (b <= c) & (c <= d)
As the doc says:
The
&
operator can be used as a shorthand fornp.logical_and
on boolean ndarrays.
Answered By - Kelly Bundy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.