有效检查numpy ndarray值是否严格增加 [英] Efficiently check if numpy ndarray values are strictly increasing

查看:203
本文介绍了有效检查numpy ndarray值是否严格增加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个numpy ndarray,我想检查每个行向量是否单调递增.

I'm having a numpy ndarray where I would like to check if each row vector is monotonically increasing.

示例:

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

预期收益:

[True, True, False]

我不确定如何有效地执行此操作,因为预计矩阵会很大(〜1000x1000),并且希望能有所帮助.

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.

推荐答案

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

找出每个元素之间的差异. np.diff 的参数可让您指定执行差异

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]])

检查每个差异是否大于0.

Check to see if each difference is greater than 0.

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

检查所有差异是否均大于0

Check to see if all the differences are > 0

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


如@Jaime所建议-检查每个元素是否大于元素左侧的元素:

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

这似乎是我的差异解决方案的速度/效率的两倍.

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

这篇关于有效检查numpy ndarray值是否严格增加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆