我有一个numpy ndarray,我想检查每个行向量是否单调递增。示例:
a = np.asarray([[1,2,3],[1,5,7],[4,3,6]]) monotonically_increasing(a)
预期回报:
[True, True, False]
我不完全确定如何有效地做到这一点,因为矩阵预计将相当大(~ 1000 x1000),并希望得到一些帮助。
af7jpaap1#
>>> import numpy as np >>> a = np.asarray([[1,2,3],[1,5,7],[4,3,6]])
np.diff有一个参数,可以让您指定轴来 * 执行diff*
np.diff
>>> np.diff(a) array([[ 1, 1], [ 4, 2], [-1, 3]])
检查每个差值是否大于0。
>>> np.diff(a) > 0 array([[ True, True], [ True, True], [False, True]], dtype=bool)
检查是否所有差异都〉0
>>> np.all(np.diff(a) > 0) False >>>
正如@Jaime所建议的,检查每个元素是否大于其左边的元素:
np.all(a[:, 1:] >= a[:, :-1], axis=1)
这似乎是两倍的速度/效率比我的差异解决方案。
w6mmgewl2#
你可以创建一个这样的函数:
def monotonically_increasing(l): return all(x < y for x, y in zip(l, l[1:]))
然后检查子列表的子列表
[monotonically_increasing(sublist) for sublist in a]
lxkprmvk3#
为了添加@Jaime和所有提供的答案,以获得违规的确切位置,除了确定它们是否严格增加或减少之外,我将其链接如下
a = np.array( [[1,2,3], [5,4,3], [4,5,6], [4,6,3]]) a[np.where ( np.invert (np.all(a[:, 1:] >= a[:, :-1], axis=1)) ) ] Result: array([[5, 4, 3], [4, 6, 3]])
dddzy1tm4#
还有一个问题与如何处理从@igorkf严格递减有关。我将这个答案组合成一个有用的函数。
def check_monotonicity (data: np.array, increasing: bool, axis: int) -> np.array : if increasing: # strictly increasing return data [np.where ( np.invert ( (np.all(data[:, 1:] >= data[:, :-1], axis=axis)) ) ) ] else: # strictly decreasing return data [np.where ( np.invert ( (np.all(data[:, 0:-1] >= data[:, 1:], axis=axis)) ) ) ]
4条答案
按热度按时间af7jpaap1#
np.diff
有一个参数,可以让您指定轴来 * 执行diff*检查每个差值是否大于0。
检查是否所有差异都〉0
正如@Jaime所建议的,检查每个元素是否大于其左边的元素:
这似乎是两倍的速度/效率比我的差异解决方案。
w6mmgewl2#
你可以创建一个这样的函数:
然后检查子列表的子列表
lxkprmvk3#
为了添加@Jaime和所有提供的答案,以获得违规的确切位置,除了确定它们是否严格增加或减少之外,我将其链接如下
dddzy1tm4#
还有一个问题与如何处理从@igorkf严格递减有关。我将这个答案组合成一个有用的函数。