python - Pandas `agg` 列出, "AttributeError/ValueError: Function does not reduce"

标签 python pandas group-by pandas-groupby

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

groupby.agg 似乎是执行这些分组和计算的自然方式。

但是,groupby.agg 之间似乎存在差异。和groupby.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

最佳答案

经过大量调查,我发现这是一个错误,将在 pandas 的 future 版本中修复。

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.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))):
                    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

关于python - Pandas `agg` 列出, "AttributeError/ValueError: Function does not reduce",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48910956/

相关文章:

python - 如何将已更改的 QComboBox 的单元格行检索为 QTableWidget 的 QCellWidget?

python - Plone 如何为事件添加内容规则,该事件在结束日期后应移至另一个文件夹

python - 在python中将文本文件转换为.xlsx

python - 如何更改 pd DataFrame 的结构,将行值添加到列?

MySQL group by min() 和限制输出

sql - Postgresql 中连续相同符号行的总和

python - 在 linux 中使用 python 创建进程树,如 pstree 命令

python - tkinter .after() 秒和分

python - pybrain - ClassificationDataSet - 如何理解使用 SoftmaxLayer 时的输出

mysql - 分组并计数不返回我期望的