Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently check if numpy ndarray values are strictly increasing

Tags:

I'm having a numpy ndarray where I would like 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 return:

[True, True, False] 

I'm not entirely sure how to efficiently do this, since the matrices are expected to be quite large (~1000x1000), and was hoping for some help.

like image 583
Jimmy C Avatar asked Jun 09 '15 13:06

Jimmy C


People also ask

Is a NumPy Ndarray is faster than a built in list?

Because the Numpy array is densely packed in memory due to its homogeneous type, it also frees the memory faster. So overall a task executed in Numpy is around 5 to 100 times faster than the standard python list, which is a significant leap in terms of speed.

Is Ndarray in NumPy better than a list?

Numpy data structures perform better in: Size - Numpy data structures take up less space. Performance - they have a need for speed and are faster than lists. Functionality - SciPy and NumPy have optimized functions such as linear algebra operations built in.

How do you compare Ndarray?

Method 1: We generally use the == operator to compare two NumPy arrays to generate a new array object. Call ndarray. all() with the new array object as ndarray to return True if the two NumPy arrays are equivalent.

What is the difference between Ndarray and array in NumPy?

numpy. array is just a convenience function to create an ndarray ; it is not a class itself. You can also create an array using numpy. ndarray , but it is not the recommended way.


1 Answers

>>> import numpy as np >>> a = np.asarray([[1,2,3],[1,5,7],[4,3,6]]) 

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

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

Check to see if each difference is greater than 0.

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

Check to see if all the differences are > 0

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

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

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

Which appears to be about twice as fast/efficient as my diff solution.

like image 175
4 revs Avatar answered Nov 11 '22 15:11

4 revs