groupby上的pandas concat数组

时间:2015-09-16 10:42:53

标签: python pandas

我有一个由group by:

创建的DataFrame
agg_df = df.groupby(['X', 'Y', 'Z']).agg({
    'amount':np.sum,
    'ID': pd.Series.unique,
})

我在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,
})

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

ValueError: Function does not reduce

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

               |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] |

预期结果应为

          |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]     |

最终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,
})

EDIT2: 在我的案例中另一个解决方案是:

combine_ids = lambda x: set(np.hstack(x.values))

EDIT3: 由于Pandas聚合函数实现的实现,似乎无法避免set()作为结果值。 https://stackoverflow.com/a/16975602/3142459

中的详细信息

2 个答案:

答案 0 :(得分:2)

如果您使用套装作为您的类型(我可能会这样做)很好,那么我会选择:

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)})

......对我有用。出于某种原因,lambda s: set(s)可以正常工作,但是设置不起作用(我猜测某些地方的熊猫没有正确地进行鸭子打字)。

如果您的数据很大,您可能需要以下代替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())

答案 1 :(得分:0)

当您的聚合函数返回一个Series时,pandas不一定知道您希望将其打包到单个单元格中。作为一种更通用的解决方案,只需将结果明确强制转换为列表即可。

agg_df = df.groupby(['X', 'Y', 'Z']).agg({
    'amount':np.sum,
    'ID': lambda x: list(x.unique()),
})