3
我試圖按多個列進行分組,並對它們進行分組,以便它們在分組後成爲列表。Pandas - Groupby多列
目前,DataFrame
看起來是這樣的:
我試圖用這個:
grouped = DataFrame.groupby(['jobname', 'block'], axis=0)
DataFrame= grouped.aggregate(lambda x: list(x))
然而,當我申請這IPython的,它給了我這個錯誤:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-221-97113b757fa1> in <module>()
----> 1 cassandraFrame_2 = grouped.aggregate(lambda x: list(x))
2 cassandraFrame_2
/usr/local/lib/python2.7/dist-packages/pandas/core/groupby.pyc in aggregate(self, arg, *args, **kwargs)
2867
2868 if self.grouper.nkeys > 1:
-> 2869 return self._python_agg_general(arg, *args, **kwargs)
2870 else:
2871
/usr/local/lib/python2.7/dist-packages/pandas/core/groupby.pyc in _python_agg_general(self, func, *args, **kwargs)
1166 for name, obj in self._iterate_slices():
1167 try:
-> 1168 result, counts = self.grouper.agg_series(obj, f)
1169 output[name] = self._try_cast(result, obj)
1170 except TypeError:
/usr/local/lib/python2.7/dist-packages/pandas/core/groupby.pyc in agg_series(self, obj, func)
1633 return self._aggregate_series_fast(obj, func)
1634 except Exception:
-> 1635 return self._aggregate_series_pure_python(obj, func)
1636
1637 def _aggregate_series_fast(self, obj, func):
/usr/local/lib/python2.7/dist-packages/pandas/core/groupby.pyc in _aggregate_series_pure_python(self, obj, func)
1667 if (isinstance(res, (Series, Index, np.ndarray)) or
1668 isinstance(res, list)):
-> 1669 raise ValueError('Function does not reduce')
1670 result = np.empty(ngroups, dtype='O')
1671
ValueError: Function does not reduce
最終,我想g將相同的作業名組合在一起,但是數據是一個元組列表,現在它是一個3元組元組。
例如:
jobname block data
Complete-Test Simple_buff (tuple_1)
Complete-Test Simple_buff (tuple_2)
總結:
jobname block data
Complete-Test Simple_buff [(tuple_1),(tuple_2)]
我能集團通過jobname
,但是,這種聚合了block
在一起,但我想保持獨立blocks
。
有人能指引我走向正確的方向嗎?
感謝
你能表明你希望獲得的結果?錯誤消息說你需要給'aggregate'一個縮減函數,即爲每個組返回一個標量(而不是一個列表或數組) – joris
@joris,我已經更新了我的問題以獲得我想要的內容。基本上,如果jobname和block是相同的,那麼將兩個元組合在一起以形成兩個元組的列表。有時候只有1個元組,有時候要組合2個或更多的元組。 – user1157751
回溯表明聚合函數不能返回一個列表,但是一個元組可以工作。 –