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

如何基于Pandas DataFrame构建方法对比统计表格?

Pandas构建方法对比矩阵

原始数据

给定的DataFrame如下:

import pandas as pd

df = pd.DataFrame([['A', 'M1', 1], ['A', 'M2', 4], 
                   ['B', 'M1', 3], ['B', 'M2', 2],
                   ['C', 'M1', 5], ['C', 'M2', 0]],
                   columns=['task', 'method', 'value'])

对应表格:

taskmethodvalue
AM11
AM24
BM13
BM22
CM15
CM20

需求说明

需要生成对比表格,其中行r、列c的值代表方法r在多少个任务中的数值高于方法c,目标表格如下:

method        M1   M2
method               
M1             0    2
M2             1    0

解决方案

步骤1:转换为宽表

先将数据按task分组,把每个方法的value转为列,方便同任务下的方法对比:

wide_df = df.pivot(index='task', columns='method', values='value')

转换后的宽表:

taskM1M2
A14
B32
C50

步骤2:构建对比矩阵

遍历所有方法组合,统计每个方法对满足r值 > c值的任务数量:

methods = wide_df.columns.tolist()
compare_matrix = {}

for r in methods:
    compare_matrix[r] = {}
    for c in methods:
        # 统计当前方法对的符合条件的任务数
        count = (wide_df[r] > wide_df[c]).sum()
        compare_matrix[r][c] = count

# 转换为目标格式的DataFrame
result_df = pd.DataFrame(compare_matrix).T
result_df.index.name = 'method'
result_df.columns.name = 'method'

最终结果

运行上述代码后,result_df即为目标对比表格:

method        M1   M2
method               
M1             0    2
M2             1    0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 08:09:24