Reputation: 2103
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).
Upvotes: 0
Views: 99
Reputation: 799
Something like this can be better implemented in numpy, has less overhead
x = np.array([[3, 6, 7, -2, -5, -1, -1],[3, 1, -1, -2, -1, -5, -1]])
allpositive = (x>0).all(axis=1)
allnegative = (x<0).all(axis=1)
mixed = ((x>0)|(x<0)).any(axis=1)
Results for your particular dataset:
>>> x
array([[ 3, 6, 7, -2, -5, -1, -1],
[ 3, 1, -1, -2, -1, -5, -1]])
>>> allpositive
array([False, False])
>>> allnegative
array([False, False])
>>> mixed
array([ True, True])
Adapt the behavior to cover the sign of 0 to your taste.
Upvotes: 0
Reputation: 30032
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.
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))))
Upvotes: 0
Reputation: 64
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.
Upvotes: 1