pandas在分组上连接数组

13

我有一个由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 前的 DataFrame 如下:

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

编辑2:另外一个适用于我的情况的解决方案是:

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

编辑3: 由于Pandas聚合函数的实现,似乎无法避免set()作为结果值。详情请参见https://dev59.com/1GQn5IYBdhLWcg3wP1NU#16975602


你可以在这里找到一些关于扁平化(任意深度嵌套)序列的更多教程:链接 - unutbu
据我所知,您无法从聚合方法中返回列表或数组。 - Nader Hisham
2个回答

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

...这对我很有帮助。由于某种原因,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())

2

当你的聚合函数返回一个Series时,pandas不一定知道你想要将其打包成单个单元格。作为更通用的解决方案,只需显式地将结果强制转换为列表。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接