Pandas`agc`列表," AttributeError / ValueError:函数不会减少"

时间:2018-02-21 16:34:00

标签: python pandas group-by pandas-groupby

通常,当我们使用pandas执行groupby操作时,我们可能希望在多个系列中应用多个函数。

{{3}}似乎是执行这些分组和计算的自然方式。

但是,groupby.agggroupby.apply的实施方式之间似乎存在差异,因为我无法使用agg分组到列表。元组和集合工作正常,这表明你只能通过agg聚合到不可变类型。通过groupby.apply,我可以直接将一个系列汇总到一个列表而没有任何问题。

下面是一个完整的例子。功能(1),(2),(3)成功完成。 (4)回复# ValueError: Function does not reduce

import pandas as pd

df = pd.DataFrame([['Bob', '1/1/18', 'AType', 'blah', 'test', 'test2'],
                   ['Bob', '1/1/18', 'AType', 'blah2', 'test', 'test3'],
                   ['Bob', '1/1/18', 'BType', 'blah', 'test', 'test2']],
                  columns=['NAME', 'DATE', 'TYPE', 'VALUE A', 'VALUE B', 'VALUE C'])


def grouper(df, func):
    f = {'VALUE A': lambda x: func(x), 'VALUE B': 'last', 'VALUE C': 'last'}
    return df.groupby(['NAME', 'DATE', 'TYPE'])['VALUE A', 'VALUE B', 'VALUE C']\
             .agg(f).reset_index()

# (1) SUCCESS
grouper(df, set)

# (2) SUCCESS
grouper(df, tuple)

# (3) SUCCESS
df.groupby(['NAME', 'DATE', 'TYPE', 'VALUE B', 'VALUE C'])['VALUE A']\
  .apply(list).reset_index()

# (4) FAIL
grouper(df, list)

# AttributeError
# ValueError: Function does not reduce

1 个答案:

答案 0 :(得分:2)

经过多次调查,我发现这是一个错误,将在未来的熊猫版本中修复。

0.22.x groupby.py中的违规代码,请注意isinstance(res, list)

def _aggregate_series_pure_python(self, obj, func):

    group_index, _, ngroups = self.group_info

    counts = np.zeros(ngroups, dtype=int)
    result = None

    splitter = get_splitter(obj, group_index, ngroups, axis=self.axis)

    for label, group in splitter:
        res = func(group)
        if result is None:
            if (isinstance(res, (Series, Index, np.ndarray)) or
                    isinstance(res, list)):
                raise ValueError('Function does not reduce')
            result = np.empty(ngroups, dtype='O')

        counts[label] = group.shape[0]
        result[label] = res

    result = lib.maybe_convert_objects(result, try_float=0)
    return result, counts

Master branch of groupby.pyisinstance(res, list)省略:

def _aggregate_series_pure_python(self, obj, func):

        group_index, _, ngroups = self.group_info

        counts = np.zeros(ngroups, dtype=int)
        result = None

        splitter = get_splitter(obj, group_index, ngroups, axis=self.axis)

        for label, group in splitter:
            res = func(group)
            if result is None:
                if (isinstance(res, (Series, Index, np.ndarray))):
                    raise ValueError('Function does not reduce')
                result = np.empty(ngroups, dtype='O')

            counts[label] = group.shape[0]
            result[label] = res

        result = lib.maybe_convert_objects(result, try_float=0)
        return result, counts