python - 将 bool 检查与 & 结合起来不会 "short-circuts"吗?

标签 python pandas

我有一个 Pandas 系列:

2013-09-30           None
2013-10-31           None
2013-11-30    1.47701e+06
2013-12-31    1.47701e+06
2014-01-31    1.47701e+06

Freq: M, Name: test_series, dtype: object

如果我这样做:

pd.notnull(test_series) & np.sign(test_series) == 1

为什么我会收到错误:

*** TypeError: unorderable types: NoneType() < int()

为什么第一个不检查 notnull短路,当 Series 元素为 None 时,第二次检查根本没有完成?

最佳答案

我认为不是,因为 &| 可与 booelan Series 配合使用。

因此,它通过运算符 & 按元素将第一个条件中的一个 mask 与另一个 mask 结合起来。

#convert to numeric, if not possible get NaN
test_series = pd.to_numeric(test_series, errors='coerce')

mask1 = pd.notnull(test_series)
mask2 = np.sign(test_series) == 1
print (mask1)
2013-09-30    False
2013-10-31    False
2013-11-30     True
2013-12-31     True
2014-01-31     True
Name: test_series, dtype: bool

print (mask2)
2013-09-30    False
2013-10-31    False
2013-11-30     True
2013-12-31     True
2014-01-31     True
Name: test_series, dtype: bool

print (mask1 & mask2)
2013-09-30    False
2013-10-31    False
2013-11-30     True
2013-12-31     True
2014-01-31     True
Name: test_series, dtype: bool

关于python - 将 bool 检查与 & 结合起来不会 "short-circuts"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41208832/

相关文章:

python - 如何使用Python转换字节数组 b'2\x000\x006\x000\x000\x000\x00\x04\x04\x04\x0 4' to Readable character string "20600"?

python - ipython notebook pandas max 允许的列数

Python BeautifulSoup - 查找类名称以某个字符串开头的所有元素

python - pandas 两个数据框多列值比较

python - Pandas:for 循环遍历列

python - 根据条件 pandas 传播值

Python ssh 连接到交互式程序(例如,python 解释器)

python - 为给定的单词集创建 id 的简单 [pythonic] 方法

python - 当值与另一列匹配时回填 Pandas 系列中的值

python - 在 pandas 中,如何使用 "where"参数来查询日期时间索引列?