Effectively check if numpy ndarray values ​​are strict

I have a numpy ndarray where I want to check if each row vector is monotonically increasing.

Example:

a = np.asarray([[1,2,3],[1,5,7],[4,3,6]]) monotonically_increasing(a) 

Expected Revenue:

 [True, True, False] 

I am not quite sure how to do this efficiently, as the matrices are expected to be large enough (~ 1000x1000) and were hoping for some help.

+7
python numpy matrix
source share
2 answers
 >>> import numpy as np >>> a = np.asarray([[1,2,3],[1,5,7],[4,3,6]]) 

Find the difference between each item. np.diff has an argument that allows you to specify the axis to perform diff

 >>> np.diff(a) array([[ 1, 1], [ 4, 2], [-1, 3]]) 

Check if each difference is greater than 0.

 >>> np.diff(a) > 0 array([[ True, True], [ True, True], [False, True]], dtype=bool) 

Make sure all differences are> 0

 >>> np.all(np.diff(a) > 0) False >>> 

As suggested by @Jaime - check that each element is larger than the element to its left:

 np.all(a[:, 1:] >= a[:, :-1], axis=1) 

which seems to be about twice as fast / more efficient than my solution.

+13
source share

You can make a function like this:

 def monotonically_increasing(l): return all(x < y for x, y in zip(l, l[1:])) 

and then check it out, sign up for subscriptions, so

 [monotonically_increasing(sublist) for sublist in a] 
+2
source share

All Articles