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