考虑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
Run Code Online (Sandbox Code Playgroud)
问题 的
每个元素s都是numpy.array。当我尝试在组内求和时,出现错误,因为 groupby 函数期望结果为标量...(我猜测)
s.groupby(level=0).sum()
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)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
当我使用applywithnp.sum,它工作得很好。
s.groupby(level=0).apply(np.sum)
a [0, 2, 4, 6]
b [0, 2, 4, 6]
dtype: object
Run Code Online (Sandbox Code Playgroud)
问题
有没有一种优雅的方法来处理这个问题?
真正的问题我实际上想以这种方式
使用agg
s.groupby(level=0).agg(['sum', 'prod'])
Run Code Online (Sandbox Code Playgroud)
但它以同样的方式失败了。
得到这个的唯一方法是
pd.concat([g.apply(np.sum), g.apply(np.prod)],
axis=1, keys=['sum', 'prod'])
Run Code Online (Sandbox Code Playgroud)
但这并不能很好地推广到更长的变换列表。
从这个解释清楚的答案中,您可以将 ndarray 转换为列表,因为 pandas 似乎正在检查输出是否是 ndarray,这就是您引发此错误的原因:
s.groupby(level=0).agg({"sum": lambda x: list(x.sum()), "prod":lambda x: list(x.prod())})
Run Code Online (Sandbox Code Playgroud)
输出[249]:
sum prod
a [0, 2, 4, 6] [0, 1, 4, 9]
b [0, 2, 4, 6] [0, 1, 4, 9]
Run Code Online (Sandbox Code Playgroud)