Issue
suppose that I have the following NumPy array:
x = np.array([0,1,2,3,4,5])
I'd like to check if the numbers are in ascending order, i.e., if exists a number larger than the number before, it should warn me. I believe that I can do it with the any
syntax, but I'm not sure how. For instance, I've been trying:
if any(x[i] < x[i-1] for i in range(len(x))):
print('Warning!')
But it's not working properly. It should activate the warning in arrays like [0,2,1,3,4,5]
, and so on. Could someone please help me fix this issue? Thank you in advance!
Solution
You can use np.diff
and check if it is all positive.
>>> import numpy as np
>>> arr = np.array([0,1,2,3,4,5])
>>> np.diff(arr)
array([1, 1, 1, 1, 1])
>>> (np.diff(arr) >= 0).all()
True
Or
>>> arr = np.array([0,2,1,3,4,5])
>>> np.diff(arr)
array([ 2, -1, 2, 1, 1])
>>> (np.diff(arr) >= 0).all()
False
Note, you could use any
/all
here as well, but you should try to use numpy operations on numpy arrays. But just for clarification, you basically wanted all(arr[i] <= arr[i+1] for i in range(len(arr) -1))
.
And note, I'm expressing things in terms of "all", but you can use "any" equivalently:
(np.diff(arr) < 0).any()
And of course, any(arr[i] > arr[i+1] for i in range(len(arr) -1))
.
Finally, you must decide how to treat the case of no change, i.e. when the difference between subsequent elements is 0. Since you used the terminology "ascending order", typically, [1, 1, 2, 3]
i considered in ascending order so I've used that convention above (edited since originally posted))
Answered By - juanpa.arrivillaga
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.