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

如何对DataFrame进行透视并转置单行,将列转为二级多重索引

Pandas DataFrame透视转换实现指定结构

需求说明

需要将给定的DataFrame进行透视转换,将现有列转为二级行标识,最终得到指定格式的结果。

原DataFrame结构

Type        VC  C   B   Security
0   Standard    2   2   2       A
1   Standard    16  13  0       B
2   Standard    52  35  2       C
3   RI          10  10  0       A
4   RI          10  15  31      B
5   RI          10  15  31      C

期望结果结构

Type            A   B  C  
0   Standard VC     2   16 52
1   Standard C      2   13 35
2   Standard B      2   0  2
3   RI       VC     10  10 10
4   RI       C      10  15 15
5   RI       B      0   31 31

实现代码

import pandas as pd

# 1. 创建原DataFrame
df = pd.DataFrame({
    'Type': ['Standard', 'Standard', 'Standard', 'RI', 'RI', 'RI'],
    'VC': [2, 16, 52, 10, 10, 10],
    'C': [2, 13, 35, 10, 15, 15],
    'B': [2, 0, 2, 0, 31, 31],
    'Security': ['A', 'B', 'C', 'A', 'B', 'C']
})

# 2. 重塑数据:将VC/C/B列转为行变量
melted_df = df.melt(id_vars=['Type', 'Security'], var_name='Metric', value_name='Value')

# 3. 透视转换:设置行标识为Type+Metric,列为Security
result_df = melted_df.pivot(index=['Type', 'Metric'], columns='Security', values='Value').reset_index()

# 4. 调整顺序以匹配目标结构
result_df['Metric'] = pd.Categorical(result_df['Metric'], categories=['VC', 'C', 'B'], ordered=True)
result_df = result_df.sort_values(['Type', 'Metric']).reset_index(drop=True)

# 5. 合并Type和Metric列,生成目标显示格式
result_df['Type'] = result_df['Type'] + ' ' + result_df['Metric']
result_df = result_df.drop('Metric', axis=1)

# 查看结果
print(result_df)

代码说明

  • melt:将宽表转为长表,把VC/C/B这三个指标列转为行数据,方便后续透视。
  • pivot:将Security作为列,Type和Metric作为行标识,重新组织数据结构。
  • 分类排序:通过指定Metric的分类顺序,确保结果中VC/C/B的顺序和目标一致。
  • 列合并:将Type和Metric合并为一列,匹配目标的显示格式。

内容的提问来源于stack exchange,提问作者Pier-Olivier Marquis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 07:00:59