首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >过载Pandas操作员

过载Pandas操作员
EN

Stack Overflow用户
提问于 2022-09-11 01:37:10
回答 1查看 51关注 0票数 0

我试图子类一个熊猫系列和超载的运算符,但不知道为什么我得到一个递归错误。以下是可复制性最低的示例:

代码语言:javascript
复制
import pandas as pd

class MySeries(pd.Series):

    def __mul__(self, other):
        print('hello!')
        return super().mul(other)

MySeries([1,2,3]) * 1

我得到以下错误:

代码语言:javascript
复制
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

只有当我将子类实例乘以一个整数时才会发生错误,但是如果我将子类实例乘以一个instance

  • calling MySeries([1,2,3]).mul(1)或另一个子类MySeries([1,2,3]).mul(1)也会发生错误。如果删除MySeries.

  • This中的__mul__方法,与其他操作符(__add____sub__等)

  • 一起发生,则不会中断--我可以用完全相同的代码来子类DataFrame并覆盖__mul__方法,而*运算符的行为与预期相同(即只有在子类为Series)

时才会发生这种情况。

几个小时以来,我一直把头撞在桌子上--任何洞察力都是值得赞赏的!谢谢!

熊猫版1.4.3;python 3.9.5

EN

回答 1

Stack Overflow用户

发布于 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)

以下代码提供了所需的结果:

代码语言:javascript
复制
import pandas as pd

class MySeries(pd.Series):

    def __mul__(self, other):
        print('hello!')
        return super().__mul__(other)

MySeries([1,2,3]) * 2
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73676256

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档