如何基于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'])
对应表格:
| task | method | value |
|---|---|---|
| A | M1 | 1 |
| A | M2 | 4 |
| B | M1 | 3 |
| B | M2 | 2 |
| C | M1 | 5 |
| C | M2 | 0 |
需求说明
需要生成对比表格,其中行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')
转换后的宽表:
| task | M1 | M2 |
|---|---|---|
| A | 1 | 4 |
| B | 3 | 2 |
| C | 5 | 0 |
步骤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
相关产品推荐
相关产品推荐

