这是我之前一个问题的后续帖子:
Check whether numpy array row is smaller than the next
假设我有以下 numpy 数组:
a=np.reshape(np.array([[79,np.nan,87,77,92,133,99,121,103,118,126,
133,131,67]]),(7,2))
In [1]: a
Out[1]:
array([[ 79., nan],
[ 87., 77.],
[ 92., 133.],
[ 99., 121.],
[ 103., 118.],
[ 126., 133.],
[ 131., 67.]])
我想创建一个新的列或数组,这将是一个 True/False 指标,用于测试以下命题:
a[-1, 0] < a[1:, 0] and a[-1, 1] > a[1:, 1]
我期望的结果如下:
False (because the first value of column 1 is nan)
False
True
True
False
True
False
我已经尝试了上一篇文章中描述的解决方案的不同变体,但到目前为止我都没有成功。
编辑:
想法是测试是否 87<92 同时 77>133 是否为 False。然后 92<99 和 133>121 为真等等。
您将使用与 Tai's answer 完全相同的策略在您之前的帖子中:
b = np.diff(a, axis=0)
[[ 8. nan]
[ 5. 56.]
[ 7. -12.]
[ 4. -3.]
[ 23. 15.]
[ 5. -66.]]
现在您使用逻辑函数 np.logical_and
在数组 b
上。因为你总是想要一个 trailing False,我们可以直接附加它:
result = np.logical_and(b[:,0] > 0, b[:,1] < 0)
result = np.append(result, np.array([False]))
[False False True True False True False]
(根据您的意见编辑了我的帖子)
注意:将值与nan
进行比较将始终返回False
。因此,如果 nan
出现在中间的某行中,它总是会生成 两 行,这些行的计算结果为 False
。
我是一名优秀的程序员,十分优秀!