0
考虑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
问题
有处理这个优雅的方式?
真正的问题
其实我是想用这种方式
s.groupby(level=0).agg(['sum', 'prod'])
使用agg
,但它以同样的方式失败。
得到这个唯一的办法就是
pd.concat([g.apply(np.sum), g.apply(np.prod)],
axis=1, keys=['sum', 'prod'])
但这并不能一概而论很好地变换较长的列表。
我觉得你的工作很漂亮! –
@StevenG我的歉意,我之前删除了这个问题,因为它形成了病态。我不得不跑,现在我试图磨砺这个问题。我真正的问题是,我不能聚合没有使用我的解决方法和'pd.concat' – piRSquared
我现在找不到一个好的链接,但是,非标量元素并不真正支持。 – DSM