我试图子类一个熊猫系列和超载的运算符,但不知道为什么我得到一个递归错误。以下是可复制性最低的示例:
import pandas as pd
class MySeries(pd.Series):
def __mul__(self, other):
print('hello!')
return super().mul(other)
MySeries([1,2,3]) * 1我得到以下错误:
hello!
...
hello!
File "/home/jibi/.local/lib/python3.9/site-packages/pandas/core/ops/__init__.py", line 197, in flex_wrapper
return op(self, other)
File "<stdin>", line 4, in __mul__
...
File "/home/jibi/.local/lib/python3.9/site-packages/pandas/core/ops/__init__.py", line 197, in flex_wrapper
return op(self, other)
File "<stdin>", line 4, in __mul__
packages/pandas/core/ops/common.py", line 90, in get_op_result_name
if isinstance(right, (ABCSeries, ABCIndex)):
RecursionError: maximum recursion depth exceeded意见:
method
mul方法__rmul__ _constructor method (https://pandas.pydata.org/docs/development/extending.html#subclassing-pandas-data-structures)只有当我将子类实例乘以一个整数时才会发生错误,但是如果我将子类实例乘以一个instance
MySeries([1,2,3]).mul(1)或另一个子类MySeries([1,2,3]).mul(1)也会发生错误。如果删除MySeries.
__mul__方法,与其他操作符(__add__、__sub__等)
DataFrame并覆盖__mul__方法,而*运算符的行为与预期相同(即只有在子类为Series)时才会发生这种情况。
几个小时以来,我一直把头撞在桌子上--任何洞察力都是值得赞赏的!谢谢!
熊猫版1.4.3;python 3.9.5
发布于 2022-09-11 19:59:53
需要注意的是,mul和__mul__是pd.Series中的两个不同的函数。双下划线主要是Python中表示私有变量的约定。
当您调用MySeries.__mul__:首先,这将导致调用super().mul(..),其内部逻辑在熊猫中被定义为调用MySeries的__mul__函数,然后调用super().mul(..)等等。因此,无限递归。
解决方案是将super().mul(other)替换为super().__mul__(other)
以下代码提供了所需的结果:
import pandas as pd
class MySeries(pd.Series):
def __mul__(self, other):
print('hello!')
return super().__mul__(other)
MySeries([1,2,3]) * 2https://stackoverflow.com/questions/73676256
复制相似问题