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
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
Use any
>>> s = pd.Series([1,5,3,-1,7])
>>> any(s<0)
True
%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 You can use Series.lt
:
s = pd.Series([1,5,3,-1,7])
s.lt(0).any()
Output:
True
lt
stands for 'less than' –
Drye 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
© 2022 - 2024 — McMap. All rights reserved.
(s<0).sum()>0
? – Brigittebriley(s<0).any()
– Brigittebrileyany(s<0)
– Rajasthan