如何检查列的任何值是否在Pandas中处于某个范围内(两个值之间)? [英] How to check if any value of a column is in a range (in between two values) in Pandas?

查看:807
本文介绍了如何检查列的任何值是否在Pandas中处于某个范围内(两个值之间)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DataFrame,我想检查列的任何值(v)是否满足x<=v<=y.

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

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

我得到的错误是ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().,但是我已经在使用any()

The error I get is ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). But I am using any() already!

那么这是什么问题?为什么它与==一起使用而不与x<=v<=y一起使用?

So what's the problem here? Why does it work with == but not with x<=v<=y?

推荐答案

使用 between 来执行此操作,它还支持通过inclusive arg:

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

然后您在上面致电any:

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

Out[132]:
True

这篇关于如何检查列的任何值是否在Pandas中处于某个范围内(两个值之间)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆