Search code examples
pythonpandasseriesmembershipany

Check if a pandas Series has at least one item greater than a value


The following code will print True because the Series contains at least one element that is greater than 1. However, it seems a bit un-Pythonic. Is there a more Pythonic way to return True if a Series contains a number that is greater than a particular value?

import pandas as pd

s = pd.Series([0.5, 2])
print True in (s > 1)          # True

Not only is the above answer un-Pythonic, it will sometimes return an incorrect result for some reason. For example:

s = pd.Series([0.5])
print True in (s < 1)          # False

Solution

  • You could use any method to check if that condition is True at least for the one value:

    In [36]: (s > 1).any()
    Out[36]: True