如何检测numpy数组中元素的符号变化 [英] How to detect a sign change for elements in a numpy array

查看:118
本文介绍了如何检测numpy数组中元素的符号变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有正负值的numpy数组.

I have a numpy array with positive and negative values in.

a = array([1,1,-1,-2,-3,4,5])

我想创建另一个数组,该数组在发生符号变化的每个索引处都包含一个值(例如,如果当前元素为正,而前一个元素为负,反之亦然).

I want to create another array which contains a value at each index where a sign change occurs (For example, if the current element is positive and the previous element is negative and vice versa).

对于上面的数组,我希望得到以下结果

For the array above, I would expect to get the following result

array([0,0,1,0,0,1,0])

或者,在数组中出现符号变化的位置的列表或布尔列表(而不是0和1)也可以.

Alternatively, a list of the positions in the array where the sign changes occur or list of booleans instead of 0's and 1's is fine.

推荐答案

类似

a = array([1,1,-1,-2,-3,4,5])
asign = np.sign(a)
signchange = ((np.roll(asign, 1) - asign) != 0).astype(int)
print signchange
array([0, 0, 1, 0, 0, 1, 0])

现在,numpy.roll进行循环移位,因此,如果最后一个元素的符号与第一个元素不同,则signchange数组中的第一个元素将为1.如果不需要,当然可以做一个简单的

Now, numpy.roll does a circular shift, so if the last element has different sign than the first, the first element in the signchange array will be 1. If this is not desired, one can of course do a simple

signchange[0] = 0

另外,np.sign认为0拥有自己的正负号,不同于正值或负值.例如.即使零线仅交叉"一次,[-1,0,1]的"signchange"数组仍为[0,1,1].如果不希望这样,可以插入行

Also, np.sign considers 0 to have it's own sign, different from either positive or negative values. E.g. the "signchange" array for [-1,0,1] would be [0,1,1] even though the zero line was "crossed" only once. If this is undesired, one could insert the lines

sz = asign == 0
while sz.any():
    asign[sz] = np.roll(asign, 1)[sz]
    sz = asign == 0

在第一个示例的第2行和第3行之间.

between lines 2 and 3 in the first example.

这篇关于如何检测numpy数组中元素的符号变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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