python - pandas 的元素二进制 bool 操作数具有相同长度元素持有不同索引的规则是什么?

标签 python pandas

我一直在我的代码库中应用一些二进制 bool 运算符,并遇到了一个让我非常惊讶的错误。我重建了一个最小的工作示例来演示下面的行为......

import pandas
s = pandas.Series( [True]*4 )
d = pandas.DataFrame( { 'a':[True, False, True, False] , 'b':[True]*4 } )

print(d)
       a     b
0   True  True
1  False  True
2   True  True
3  False  True

print( s[0:2] )
0    True
1    True
dtype: bool

print( d.loc[ d['a'] , 'b' ] )
0    True
2    True
dtype: bool

print( s[0:2] & d.loc[ d['a'] , 'b' ] )
0     True
1    False
2    False

最后一条语句的值让我完全惊讶,因为它产生了 3 个元素。意识到这里索引的影响,我手动重置索引以产生我预期的结果。

s[0:2].reset_index(drop=True) & d.loc[ d['a'] , 'b' ].reset_index( drop=True )
0    True
1    True

不用说,我需要重新访问文档并掌握如何在此处应用索引规则。任何人都可以逐步解释该运算符如何处理混合索引吗?

================================================

只是为了对来自类似 R 背景的人进行比较,R 的 data.frame 等效操作产生了我所期望的结果......

> a = c(TRUE,FALSE,TRUE,FALSE)
> b = c(TRUE,TRUE,TRUE,TRUE)
> 
> d = data.frame( a, b )
> d
      a    b
1  TRUE TRUE
2 FALSE TRUE
3  TRUE TRUE
4 FALSE TRUE
> s = c( TRUE,TRUE,TRUE,TRUE)
> s
[1] TRUE TRUE TRUE TRUE
>
> d[ d$a , 'b']
[1] TRUE TRUE
>
> s[0:2]
[1] TRUE TRUE
> s[0:2] & d[ d$a , 'b']
[1] TRUE TRUE

最佳答案

您正在比较具有不同指数的两个系列

s[0:2]

0    True
1    True
dtype: bool

d.loc[ d['a'] , 'b']

0    True
2    True
dtype: bool
<小时/>

pandas 需要对齐索引然后进行比较。

s[0:2] & d.loc[ d['a'] , 'b']

0     True  # True from both indices therefore True
1    False  # Only True from s[0:2] and missing from other therefore False
2    False  # Only True from d and missing from other therefore False
dtype: bool

关于python - pandas 的元素二进制 bool 操作数具有相同长度元素持有不同索引的规则是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45311209/

相关文章:

python - 将 pandas 列四舍五入到年份

python - seaborn:因子图中的单独组

python-3.x - 使用 panda 数据帧 groupby 中的百分位数删除异常值

python - Numpy ndarray 乘法

python - 如何使用pytest为斐波那契制作测试类或函数?

javascript - 扩展 Bokeh 以匹配 D3.js

python - pandas 中行之间的减法 - python

python - DataFrame 可选 "condition"不过滤任何内容

Python 3.x - 如何让我的程序在无效时不计算部分?

python - 计算两个日期之间的差异