python - Pandas 中 boolean 索引的逻辑运算符

标签 python pandas dataframe boolean filtering

我在 Pandas 中使用 boolean 索引。

问题是为什么声明:

a[(a['some_column']==some_number) & (a['some_other_column']==some_other_number)]

工作正常,而

a[(a['some_column']==some_number) and (a['some_other_column']==some_other_number)]

出错退出?

例子:

a = pd.DataFrame({'x':[1,1],'y':[10,20]})

In: a[(a['x']==1)&(a['y']==10)]
Out:    x   y
     0  1  10

In: a[(a['x']==1) and (a['y']==10)]
Out: ValueError: The truth value of an array with more than one element is ambiguous.     Use a.any() or a.all()

最佳答案

当你说

(a['x']==1) and (a['y']==10)

您隐含地要求 Python 将 (a['x']==1)(a['y']==10) 转换为 boolean 值.

NumPy 数组(长度大于 1)和 Pandas 对象(如 Series)没有 boolean 值——换句话说,它们引发

ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().

当用作 boolean 值时。那是因为它是 unclear when it should be True or False .如果它们的长度不为零,一些用户可能会认为它们是 True,例如 Python 列表。仅当 所有 其元素为 True 时,其他人可能希望它为 True。如果 任何 元素为 True,则其他人可能希望它为 True。

因为有太多相互矛盾的期望,NumPy 和 Pandas 的设计者拒绝猜测,而是引发 ValueError。

相反,您必须明确,通过调用 empty()all()any() 方法来指示哪些行为你想要的。

但是,在这种情况下,您似乎不需要 boolean 评估,而是需要 element-wise 逻辑与。这就是 & 二元运算符的作用:

(a['x']==1) & (a['y']==10)

返回一个 boolean 数组。


顺便说一下,alexpmil notes , 括号是强制性的,因为 & 具有更高的 operator precedence==.

没有括号,a['x']==1 & a['y']==10 将被计算为 a['x'] == (1 & a['y']) == 10 这又相当于链式比较 (a['x'] == (1 & a['y'])) 和 ( (1 & a['y']) == 10)。这是 Series and Series 形式的表达式。 and 与两个 Series 一起使用将再次触发与上面相同的 ValueError。这就是括号是强制性的原因。

关于python - Pandas 中 boolean 索引的逻辑运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21415661/

相关文章:

python - 使用列表中的数据以唯一的索引顺序填充 Pandas 数据框?

python - 使用条件更改 numpy 数组中的每个值

python - 如何通过 Django App 调用 Scrapy Spider

python - 在 if 语句中将 value 转换为 bool 有什么意义吗?

python - 有条件地替换数据框列中的部分字符串

python - 如何比较 Pandas 数据框列中可用的十进制数?

Python - 并行读取多个大文件并单独生成它们

python - 加速 pandas 上的复杂功能

python - Pandas 0.19.2 read_excel IndexError : List index out of range

python - 如何水平连接 2 个数据框(按行和按列)?