python - Pandas 将行分组为列表并求和

标签 python pandas pandas-groupby multi-index

我有一个多索引 pandas 数据框,其中包含以下数据:

          F     M   
         0  5  10 30
x  y  a1  0  1  0  1
      a2  1  0  0  0
      a3  0  1  0  1
      a4  0  1  0  2
x1 y1 a1  0  1  1  4
      a2  0  1  0  1
      a3  1  1  0  1
      a4  2  1  1  2
x2 y2 a1  0  0  0  0
      a2  0  0  0  0

我想通过 (A, B) 对数据进行分组,并将 C 列与行总和合并到列表中。

所需输出:

              sex             F               M
              counts          0  5  10  30    0  5  10  30
     A  B  C
     x  y  [a1,a2,a3, a4]     1  3   3   1    0  3   0   4

     x1 y1 [a1, a2, a3, a4]   3  4   4   0    3  0   1   8

     ......

我已经尝试过df.groupby(['A', 'B']).sum()但它忽略输出数据帧中的 C 列。

<小时/>

要重现的代码

index = pd.MultiIndex(levels=[['x', 'x1', 'x2'], ['y', 'y1', 'y2'], ['a1', 'a2', 'a3', 'a4']],
           labels=[[0, 0, 0, 0, 1, 1, 1, 1, 2, 2], [0, 0, 0, 0, 1, 1, 1, 1, 2, 2], [0, 1, 2, 3, 0, 1, 2, 3, 0, 1]])

columns = pd.MultiIndex(levels=[['F', 'M'], [0, 5, 10, 30]],
           labels=[[0, 0, 1, 1], [0, 1, 2, 3]])

data = np.array([
       [0, 1, 0, 1],
       [1, 0, 0, 0],
       [0, 1, 0, 1],
       [0, 1, 0, 2],
       [0, 1, 1, 4],
       [0, 1, 0, 1],
       [1, 1, 0, 1],
       [2, 1, 1, 2],
       [0, 0, 0, 0],
       [0, 0, 0, 0]])

df = pd.DataFrame(data, index=index, columns=columns)

最佳答案

使用groupbysum来聚合数值数据,并使用apply(tuple)来聚合索引级别。

g = df.reset_index(level=-1).groupby(level=[0, 1])
res = g.sum().set_index(g.level_2.apply(tuple), append=True)

print(res)
                          F     M   
                       0  5  10 30
      level_2                     
x  y  (a1, a2, a3, a4)  1  3  0  4
x1 y1 (a1, a2, a3, a4)  3  4  2  8
x2 y2 (a1, a2)          0  0  0  0

请注意,索引只能包含可哈希值,而列表不可哈希,因此元组是次佳选择。

关于python - Pandas 将行分组为列表并求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53856833/

相关文章:

python - Pandas groupby 聚合/将特定函数应用于特定列(np.sum、sum)

python - 调试: Crawled (404) <GET >

python - Pandas 应用功能并更新数据框的副本

python - 将 N 个工作日添加到不是单位 'D' 的 Numpy datetime64

python - 将整个列与列表中的值相乘

python - 在数据框上按 groupby 平铺

python - 递归调用合并排序算法

python - 谁能解释python的相对进口?

python - 为什么 Pandas 中有 datetime.datetime ?

python分组和转置