You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据外部向量分组Pandas DataFrame列并计算行和?

按外部向量分组Pandas DataFrame列并保留缺失分组列

问题场景

现有如下DataFrame,需要按包含T2的外部向量分组计算行和,且保留所有目标分组列(包括原DataFrame中不存在的T2):

import pandas as pd
import numpy as np

matrix = pd.DataFrame(np.array( [[1,2,3,4,5], [10,20,30,40,50],[100,200,300,400,500]  ]  ))
matrix.columns =  ["T1", "T3", "T1", "T1", "T3"]
print(matrix)

输出:

T1   T3   T1   T1   T3
0    1    2    3    4    5
1   10   20   30   40   50
2  100  200  300  400  500

期望输出:

T1  T2   T3
0    8   0    7
1   80   0   70
2  800   0  700

尝试过的方法及问题

  • 直接按现有列分组求和,结果缺失T2列:
matrix.groupby(matrix.columns, axis=1).sum()

输出:

T1   T3
0    8    7
1   80   70
2  800  700
  • 直接传入目标分组列表分组,运行报错(因DataFrame中不存在T2列):
matrix.groupby(["T1", "T2", "T3"], axis=1).sum()

解决方案

方法1:分组求和后补全缺失列

先按现有列分组求和,再用reindex补全目标分组列,空值填充为0:

target_groups = ["T1", "T2", "T3"]
result = matrix.groupby(matrix.columns, axis=1).sum().reindex(target_groups, axis=1).fillna(0)
print(result)

方法2:先补全列再分组求和

先将DataFrame的列扩展为目标分组(缺失列填充0),再按分组映射求和:

target_groups = ["T1", "T2", "T3"]
# 构建分组映射,覆盖所有目标分组
group_map = {col: col for col in matrix.columns}
for g in target_groups:
    if g not in group_map:
        group_map[g] = g

# 补全列后分组求和
result = matrix.reindex(target_groups, axis=1, fill_value=0).groupby(group_map, axis=1).sum()
print(result)

两种方法均可得到符合要求的输出,方法1更简洁,方法2适用于需要复杂分组映射的场景。

内容的提问来源于stack exchange,提问作者Elizabeth_Banks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 00:30:44