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

如何使用Pandas对含4列的DataFrame执行透视操作?

解决方案

针对你的需求,这里提供两种简洁的实现方式,基于pandas完成:

方法一:拆分透视+合并列

先完成核心的透视操作,再合并与RA一一对应的ES列:

import pandas as pd

# 假设原始数据存储在df中
# 1. 执行透视:RA为行,T转成列,V为对应值
pivoted = df.pivot(index='RA', columns='T', values='V').reset_index()
# 2. 提取唯一的RA-ES映射(每个RA对应唯一ES)
es_mapping = df[['RA', 'ES']].drop_duplicates()
# 3. 合并得到最终结果
final_df = pivoted.merge(es_mapping, on='RA')

方法二:一次性透视(更高效)

利用pivot_table将RA和ES共同作为索引,直接完成透视后整理格式:

import pandas as pd

final_df = df.pivot_table(
    index=['RA', 'ES'],
    columns='T',
    values='V'
).reset_index().rename_axis(None, axis=1)

结果说明

两种方法最终都会生成你需要的目标表格结构:RA作为普通列,ee/dd/hh作为列名展示对应V值,同时保留ES列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 18:15:50