Axe*_*xel 5 numpy python-3.x pandas
pandas在不同的DataFrame/ 之间进行for操作的隐式索引匹配Series非常有用,并且在大多数情况下,它只是有效的。
但是,我偶然发现了一个无法按预期工作的示例:
import pandas as pd # 0.21.0
import numpy as np # 1.13.3
x = pd.Series([True, False, True, True], index = range(4))
y = pd.Series([False, True, True, False], index = [2,4,3,5])
# logical AND: this works, symmetric as it should be
pd.concat([x, y, x & y, y & x], keys = ['x', 'y', 'x&y', 'y&x'], axis = 1)
# x y x&y y&x
# 0 True NaN False False
# 1 False NaN False False
# 2 True False False False
# 3 True True True True
# 4 NaN True False False
# 5 NaN False False False
# but logical OR is not symmetric anymore (same for XOR: x^y vs. y^x)
pd.concat([x, y, x | y, y | x], keys = ['x', 'y', 'x|y', 'y|x'], axis = 1)
# x y x|y y|x
# 0 True NaN True False <-- INCONSISTENT!
# 1 False NaN False False
# 2 True False True True
# 3 True True True True
# 4 NaN True False True <-- INCONSISTENT!
# 5 NaN False False False
Run Code Online (Sandbox Code Playgroud)
经过研究,我发现了两点似乎很相关:
bool(np.nan)等于True,cf. /sf/answers/1098053421/|解析为np.bitwise_or,而不是np.logical_orcf。/sf/answers/2599299811/但最终,起脚似乎是大熊猫确实从铸造nan到False 在一些点。综上所述,这似乎发生在调用 之后np.bitwise_or,而我认为这应该发生在?
特别地,using np.logical_or没有帮助,因为它错过了这样pandas做的索引对齐方式,而且我也不想np.nan or False等于True。(换句话说,答案/sf/answers/2599299811/没有帮助。)
我认为,如果提供了这种出色的语法糖,它应该尽可能地一致*,并且|应该是对称的。当突然之间总是对称的东西不再存在时,调试起来真的很困难(就像我发生的那样)。
所以最后是一个问题:是否有任何可行的解决方法(例如,使某些内容超载)来挽救x|y == y|x,理想情况下,该方法应(宽松地说)nan | True == True == True | nan和nan | False == False == False | nan?
*即使De Morgan的法律分崩离析- ~(x&y)也不能完全匹配,~y|~x因为NaN仅以索引对齐方式出现(因此不受先前否定的影响)。
在对 pandas 进行一些探索之后,我发现有一个名为的函数pandas.core.ops._bool_method_SERIES,它是包装 Series 对象的布尔运算符的几个工厂函数之一。
>>> f = pandas.Series.__or__
>>> f #the actual function you call when you do x|y
<function _bool_method_SERIES.<locals>.wrapper at 0x107436bf8>
>>> f.__closure__[0].cell_contents
#it holds a reference to the other function defined in this factory na_op
<function _bool_method_SERIES.<locals>.na_op at 0x107436b70>
>>> f.__closure__[0].cell_contents.__closure__[0].cell_contents
#and na_op has a reference to the built-in function or_
<built-in function or_>
Run Code Online (Sandbox Code Playgroud)
这意味着我们理论上可以定义自己的方法来执行逻辑或正确的逻辑,首先让我们看看它实际上会做什么(请记住,如果无法执行操作,则运算符函数预计会引发 TypeError )
def test_logical_or(a,b):
print("**** calling logical_or with ****")
print(type(a), a)
print(type(b), b)
print("******")
raise TypeError("my_logical_or isn't implemented")
#make the wrapper method
wrapper = pd.core.ops._bool_method_SERIES(test_logical_or, None,None)
pd.Series.logical_or = wrapper #insert method
x = pd.Series([True, False, True, True], index = range(4))
y = pd.Series([False, True, True, False], index = [2,4,3,5])
z = x.logical_or(y) #lets try it out!
print(x,y,z, sep="\n")
Run Code Online (Sandbox Code Playgroud)
当它运行时(至少对于 pandas vs 0.19.1)
**** calling logical_or with ****
<class 'numpy.ndarray'> [True False True True nan nan]
<class 'numpy.ndarray'> [False False False True True False]
******
**** calling logical_or with ****
<class 'bool'> True
<class 'bool'> False
******
Traceback (most recent call last):
...
Run Code Online (Sandbox Code Playgroud)
所以看起来它试图用两个 numpy 数组调用我们的方法,无论出于何种原因,第二个数组的值nan已经替换为False,但不是第一个数组,这可能就是我们的对称性破裂的原因。然后当失败时它再次尝试我会假设元素明智。
因此,为了使其正常工作,您至少可以显式检查两个参数是否都是 numpy 数组,尝试将nan第一个参数的所有条目转换为Falsethen return np.logical_or(a,b)。我假设如果出现其他情况,我们只会提出错误。
def my_logical_or(a,b):
if isinstance(a, np.ndarray) and isinstance(b, np.ndarray):
a[np.isnan(a.astype(float))] = False
b[np.isnan(b.astype(float))] = False
return np.logical_or(a,b)
else:
raise TypeError("custom logical or is only implemented for numpy arrays")
wrapper = pd.core.ops._bool_method_SERIES(my_logical_or, None,None)
pd.Series.logical_or = wrapper
x = pd.Series([True, False, True, True], index = range(4))
y = pd.Series([False, True, True, False], index = [2,4,3,5])
z = pd.concat([x, y, x.logical_or(y), y.logical_or(x)], keys = ['x', 'y', 'x|y', 'y|x'], axis = 1)
print(z)
# x y x|y y|x
# 0 True NaN True True
# 1 False NaN False False <-- same!
# 2 True False True True
# 3 True True True True
# 4 NaN True True True <-- same!
# 5 NaN False False False
Run Code Online (Sandbox Code Playgroud)
因此,这可能是您的解决方法,我不建议修改,Series.__or__因为我们不知道还有谁会使用它,并且不想破坏任何期望默认行为的代码。
pandas.core.ops或者,我们可以修改第 943 行的源代码,以与相同的方式NaN用 False(或 0)填充值,因此我们将更改该行:selfother
return filler(self._constructor(na_op(self.values, other.values),
index=self.index, name=name))
Run Code Online (Sandbox Code Playgroud)
使用filler(self).values而不是self.values:
return filler(self._constructor(na_op(filler(self).values, other.values),
index=self.index, name=name))
Run Code Online (Sandbox Code Playgroud)
or这也解决了不对称的问题xor,但是,我不建议这样做,因为它可能会破坏其他代码,我个人对 pandas 没有足够的经验来确定这在不同情况下会发生什么变化。
| 归档时间: |
|
| 查看次数: |
110 次 |
| 最近记录: |