Skip to main content
 首页 » 编程设计

python之必须产生聚合值。我发誓我是

2024年10月17日8lautakyan007

考虑 pd.Series s

a = np.arange(4) 
mux = pd.MultiIndex.from_product([list('ab'), list('xy')]) 
s = pd.Series([a] * 4, mux) 
print(s) 
 
a  x    [0, 1, 2, 3] 
   y    [0, 1, 2, 3] 
b  x    [0, 1, 2, 3] 
   y    [0, 1, 2, 3] 
dtype: object 

问题
s 的每个元素都是一个 numpy.array。当我尝试在组内求和时,出现错误,因为 groupby 函数期望结果是标量...(我猜)

s.groupby(level=0).sum() 
Exception                                 Traceback (most recent call last) 
<ipython-input-627-c5b3bf6890ea> in <module>() 
----> 1 s.groupby(level=0).sum() 
 
C:\Anaconda2\lib\site-packages\pandas\core\groupby.pyc in f(self) 
    101             raise SpecificationError(str(e)) 
    102         except Exception: 
--> 103             result = self.aggregate(lambda x: npfunc(x, axis=self.axis)) 
    104             if _convert: 
    105                 result = result._convert(datetime=True) 
 
C:\Anaconda2\lib\site-packages\pandas\core\groupby.pyc in aggregate(self, func_or_funcs, *args, **kwargs) 
   2584                 return self._python_agg_general(func_or_funcs, *args, **kwargs) 
   2585             except Exception: 
-> 2586                 result = self._aggregate_named(func_or_funcs, *args, **kwargs) 
   2587  
   2588             index = Index(sorted(result), name=self.grouper.names[0]) 
 
C:\Anaconda2\lib\site-packages\pandas\core\groupby.pyc in _aggregate_named(self, func, *args, **kwargs) 
   2704             output = func(group, *args, **kwargs) 
   2705             if isinstance(output, (Series, Index, np.ndarray)): 
-> 2706                 raise Exception('Must produce aggregated value') 
   2707             result[name] = self._try_cast(output, group) 
   2708  
 
Exception: Must produce aggregated value 

变通
当我将 apply 与 np.sum 一起使用时,它工作正常。

s.groupby(level=0).apply(np.sum) 
 
a    [0, 2, 4, 6] 
b    [0, 2, 4, 6] 
dtype: object 

问题
有没有一种优雅的方式来处理这个问题?


真正的问题
我实际上想以这种方式使用 agg

s.groupby(level=0).agg(['sum', 'prod']) 

但它以同样的方式失败了。
得到这个的唯一方法是

pd.concat([g.apply(np.sum), g.apply(np.prod)], 
          axis=1, keys=['sum', 'prod']) 

但这并不能很好地推广到更长的转换列表。

请您参考如下方法:

from this well explained answer您可以将 ndarray 转换为列表,因为 pandas 似乎正在检查输出是否为 ndarray,这就是您收到此错误的原因:

s.groupby(level=0).agg({"sum": lambda x: list(x.sum()), "prod":lambda x: list(x.prod())}) 

输出[249]:

            sum          prod 
a  [0, 2, 4, 6]  [0, 1, 4, 9] 
b  [0, 2, 4, 6]  [0, 1, 4, 9]