Quick way to check if the pandas series contains a negative value
Asked Answered
M

3

9

What is the quickest way to check if the given pandas series contains a negative value.

For example, for the series s below the answer is True.

s = pd.Series([1,5,3,-1,7])

0    1
1    5
2    3
3   -1
4    7
dtype: int64
Macrography answered 7/8, 2018 at 7:5 Comment(3)
(s<0).sum()>0 ?Brigittebriley
Even shorter - (s<0).any()Brigittebriley
Even shorter - any(s<0)Rajasthan
W
19

Use any

>>> s = pd.Series([1,5,3,-1,7])
>>> any(s<0)
True
Willumsen answered 7/8, 2018 at 7:9 Comment(5)
Of all the answers, this is the fastest.Rajasthan
@MohitMotwani that depends on the size of the series and the index of the item less than zero.Japhetic
@VanPeer In that case, is there a universal fastest answer to this?Rajasthan
Plus where would this method be slower compared to the other methods mentioned?Rajasthan
nice one. For those who are curious: have checked the runtime; %timeit s.lt(0).any() results in 72.8 µs ± 2.24 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each); and %timeit any(s<0) results in 50.4 µs ± 1.65 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each). (This may be faster on more modern systems, but only as an indication)Shulman
S
5

You can use Series.lt :

s = pd.Series([1,5,3,-1,7])
s.lt(0).any()

Output:

True
Shylashylock answered 7/8, 2018 at 7:10 Comment(1)
lt stands for 'less than'Drye
A
0

Use any function:

>>>s = pd.Series([1,5,3,-1,7])
>>>any(x < 0 for x in s)
True
>>>s = pd.Series([1,5,3,0,7])
>>>any(x < 0 for x in s)
False
Alula answered 7/8, 2018 at 7:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.