代码之家  ›  专栏  ›  技术社区  ›  P. Prunesquallor

pandas pivot\u表:aggfunc参数值和引号

  •  2
  • P. Prunesquallor  · 技术社区  · 7 年前

    这两行代码仅在已传递的参数值上有所不同。我不清楚的是,为什么在第一种情况下(“count”),我们需要引号,而在第二种情况下(len),我们不需要引号。

    by_weekday1 = users.pivot_table(index='weekday', aggfunc='count')
    
    by_weekday2 = users.pivot_table(index='weekday', aggfunc=len)
    

    提前感谢!

    1 回复  |  直到 7 年前
        1
  •  1
  •   MaxU - stand with Ukraine    7 年前

    您只能将Numpy或Pandas方法(即Pandas认为是内置的[用于Pandas的])指定为字符串(引号),否则它是一个函数(也可以是Numpy函数):

    users.pivot_table(index='weekday', aggfunc='sum')
    

    类似于:

    users.pivot_table(index='weekday', aggfunc=np.sum)
    

    更新:

    这是一个 excerpt from the source files :

    def _python_agg_general(self, func, *args, **kwargs):
        func = self._is_builtin_func(func)
        ...
    

    哪里 _is_builtin_func() defined as follows :

    def _is_builtin_func(self, arg):
        """
        if we define an builtin function for this argument, return it,
        otherwise return the arg
        """
        return SelectionMixin._builtin_table.get(arg, arg)