首页 > 解决方案 > Pandas 源代码 _get_grouper 调用自己

问题描述

我在看下面的pandas源码

def _get_grouper(self, obj, validate=True):
    """
    Parameters
    ----------
    obj : the subject object
    validate : boolean, default True
        if True, validate the grouper
    Returns
    -------
    a tuple of binner, grouper, obj (possibly sorted)
    """

    self._set_grouper(obj)
    self.grouper, exclusions, self.obj = _get_grouper(self.obj, [self.key],
                                                      axis=self.axis,
                                                      level=self.level,
                                                      sort=self.sort,
                                                      validate=validate)
    return self.binner, self.grouper, self.obj

看起来 _get_grouper 递归调用自己。这不会导致无限循环吗?

我试图搜索父类,但似乎Grouper类只继承了对象类,文件中没有定义其他_get_grouper函数。

这让我有点困惑。

标签: pythonpython-3.xpandaspandas-groupby

解决方案


请注意,在类之外还有另一个_get_grouper函数,正是在此代码段中调用的函数。

如果它在_get_grouper被调用的类中是相同的,则应该将其self._get_grouper指定为该类的属性。

这是一个简单的例子来说明这一点:

class Sample():  
    def __init__(self,p):
        self.p = p
        if self.p:
            print_()
        else:
            self.print_()
    def print_(self):
        print('This is a function within the Sample class')

def print_():
    print('This is a function outside the Sample class')

s = Sample(p=True)
# This is a function outside the Sample class

s = Sample(p=False)
# This is a function within the Sample class

推荐阅读