我想对多列进行分组并聚合它们,使其在分组后成为列表。
目前,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
最终,我想要将相同的工作名称分组并组合在一起,但数据是一个元组列表,目前是一个三项元组。
例如:
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