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

如何基于指定列值将Pandas DataFrame的行转换为列

Pandas DataFrame长格式转宽格式解决方案

实现思路

  1. 为每组重复的score类别(loss/precision/recall)创建分组标识,用来区分不同的样本批次
  2. 通过melt将train和val列转为行数据,再用pivot将score与train/val拼接成新列名,完成宽格式重塑

完整代码

import pandas as pd

# 构造原始DataFrame
df = pd.DataFrame({
    'train': [0.6125, 0.8565, 0.7596, 0.0466, 0.9897, 0.9884],
    'val': [0.0827, 0.9845, 0.982, 0.0454, 0.9949, 0.9949],
    'score': ['loss', 'precision', 'recall', 'loss', 'precision', 'recall']
})

# 生成分组索引:每3行对应一套完整的loss/precision/recall指标
df['group'] = (df.index // 3) + 1

# 数据重塑流程
melted_df = df.melt(id_vars=['group', 'score'], var_name='split', value_name='value')
melted_df['col_name'] = melted_df['split'] + '_' + melted_df['score']
final_df = melted_df.pivot(index='group', columns='col_name', values='value').reset_index(drop=True)

# 调整索引从1开始,匹配目标格式
final_df.index = final_df.index + 1

print(final_df)

运行结果

train_loss  train_precision  train_recall  val_loss  val_precision  val_recall
1      0.6125           0.8565        0.7596    0.0827         0.9845        0.982
2      0.0466           0.9897        0.9884    0.0454         0.9949        0.9949

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 18:22:36