[英]Pandas `agg` to list, "AttributeError / ValueError: Function does not reduce"
通常,当我们使用groupby
执行groupby
操作时,我们可能希望在多个系列中应用多个函数。
groupby.agg
似乎是执行这些分组和计算的自然方式。
但是, groupby.agg
和groupby.apply
的实现方式之间似乎存在差异,因为我无法使用agg
分组到列表。 Tuple 和 set 工作正常,这表明您只能通过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
经过大量调查,我发现这是一个错误,将在熊猫的未来版本中修复。
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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.