groupby上的pandas concat数组

use*_*459 10 python pandas

我有一个由group by创建的DataFrame:

agg_df = df.groupby(['X', 'Y', 'Z']).agg({
    'amount':np.sum,
    'ID': pd.Series.unique,
})
Run Code Online (Sandbox Code Playgroud)

在我应用了一些过滤之后,agg_df我想要连接ID

agg_df = agg_df.groupby(['X', 'Y']).agg({ # Z is not in in groupby now
    'amount':np.sum,
    'ID': pd.Series.unique,
})
Run Code Online (Sandbox Code Playgroud)

但是我在第二个时遇到错误'ID': pd.Series.unique:

ValueError: Function does not reduce
Run Code Online (Sandbox Code Playgroud)

作为示例,第二组之前的数据帧是:

               |amount|  ID   |
-----+----+----+------+-------+
  X  | Y  | Z  |      |       |
-----+----+----+------+-------+
  a1 | b1 | c1 |  10  | 2     |
     |    | c2 |  11  | 1     |
  a3 | b2 | c3 |   2  | [5,7] |
     |    | c4 |   7  | 3     |
  a5 | b3 | c3 |  12  | [6,3] |
     |    | c5 |  17  | [3,4] |
  a7 | b4 | c6 |  2   | [8,9] |
Run Code Online (Sandbox Code Playgroud)

预期的结果应该是

          |amount|  ID       |
-----+----+------+-----------+
  X  | Y  |      |           |
-----+----+------+-----------+
  a1 | b1 |  21  | [2,1]     |
  a3 | b2 |   9  | [5,7,3]   |
  a5 | b3 |  29  | [6,3,4]   |
  a7 | b4 |  2   | [8,9]     |
Run Code Online (Sandbox Code Playgroud)

最终ID的顺序并不重要.

编辑: 我提出了一个解决方案.但它不太优雅:

def combine_ids(x):
   def asarray(elem):
      if isinstance(elem, collections.Iterable):
         return np.asarray(list(elem))
      return elem

   res = np.array([asarray(elem) for elem in x.values])
   res = np.unique(np.hstack(res))
   return set(res)

agg_df = agg_df.groupby(['X', 'Y']).agg({ # Z is not in in groupby now
    'amount':np.sum,
    'ID': combine_ids,
})
Run Code Online (Sandbox Code Playgroud)

Edit2: 在我的案例中有效的另一个解决方案是:

combine_ids = lambda x: set(np.hstack(x.values))
Run Code Online (Sandbox Code Playgroud)

编辑3:set()由于Pandas聚合功能实现的实现 ,似乎无法避免作为结果值.详情请访问/sf/answers/1188292171/

met*_*ure 4

如果您可以使用集合作为您的类型(我可能会这样做),那么我会选择:

agg_df = df.groupby(['x','y','z']).agg({
    'amount': np.sum, 'id': lambda s: set(s)})
agg_df.reset_index().groupby(['x','y']).agg({
    'amount': np.sum, 'id': lambda s: set.union(*s)})
Run Code Online (Sandbox Code Playgroud)

...这对我有用。由于某种原因,可以lambda s: set(s)工作,但 set 不行(我猜测 pandas 的某个地方没有正确执行鸭子打字)。

如果您的数据很大,您可能需要以下内容而不是lambda s: set.union(*s):

from functools import reduce
# can't partial b/c args are positional-only
def cheaper_set_union(s):
    return reduce(set.union, s, set())
Run Code Online (Sandbox Code Playgroud)