How to check if any column value is in a range (between two values) in Pandas?

I have a DataFrame and I would like to check if any of the values ​​(v) of the column satisfy x<=v<=y.

equal = any(df['columnX'] == value) # No problems here
in_between = any(x <= df['columnX'] <= y) # ValueError :/

I get an error ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()., but I'm already using it any()!

So what's the problem? Why does he work with ==, not with x<=v<=y?

+7
source share
2 answers

Use betweenit to also support whether range values ​​are included or not with inclusivearg:

In [130]:
s = pd.Series(np.random.randn(5))
s

Out[130]:
0   -0.160365
1    1.496937
2   -1.781216
3    0.088023
4    1.325742
dtype: float64

In [131]:
s.between(0,1)

Out[131]:
0    False
1    False
2    False
3     True
4    False
dtype: bool

Then you call anythe following:

In [132]:
s.between(0,1).any()

Out[132]:
True
+15
source

You can have only two conditions:

df[(x <= df['columnX']) & (df['columnX'] <= y)]

df, .

+6

Source: https://habr.com/ru/post/1658328/


All Articles