Home > Net >  Find sequences where all elements have same sign and then change sign
Find sequences where all elements have same sign and then change sign

Time:05-20

I have a series of lists with 7 elements (but could be any number). I am trying to find the lists that have all positive elements, all negative elements, and those that change sign at ANY point,

for example [3, 6, 7, -2, -5, -1, -1] or [3, 1, -1, -2, -1, -5, -1].

Note that, though I used integers in my example, the lists are actually made of floats.

I can easily find all lists that are always positive or negative, but how do I find those that change sign (it could go from positive to negative as in example or from negative to positive).

CodePudding user response:

Use the for loop to iterate from 0th element to penultimate element and compare the signs or check if the product of 2 consecutive numbers is less than 0.

If yes, then append the elements in the list.

CodePudding user response:

Assume the Series is

0     [3, 6, 7, -2, -5, -1, -1]
1    [3, 1, -1, -2, -1, -5, -1]
dtype: object

You can try get the sign of each element of list in Series and sum them.

  • If the result is 7, it means all positive,
  • If the result is -7, it means all negative
  • Otherwise, it may change the sign. (considering zero)
m = s.apply(lambda lst: sum(map(np.sign, lst)))
print(m)

0   -1
1   -3
dtype: int64

To consider zero in list, you can join the sign list and check if there is 1,-1 or -1,1

n = s.apply(lambda lst: ','.join(map(str, map(np.sign, lst))))
n = n.str.contains('1,-1|-1,1')
print(n)

0    True
1    True
dtype: bool

If you are not restrict with the 0 place, you can just check if there is 1 and -1 in the sign list

n = s.apply(lambda lst: {1, -1}.issubset(set(map(np.sign, lst))))
  • Related