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

如何在Pandas DataFrame中实现宽表转长表(透视转换)

Pandas DataFrame 宽表转长表实现方法

原始DataFrame结构

import pandas as pd

df = pd.DataFrame({
    'Id': ['123', 'abc', 'def'],
    'Phone': ['12345', '45678', '78019'],
    'Email': ['123@1233.de', 'abc@ab.de', 'def@def.de'],
    'workplace': ['test', 'test', 'test'],
    'Mailing city': ['New York', 'New York', 'New York'],
    'Mailing Stat': ['New York', 'New York', 'New York']
})

对应的表格展示:

IdPhoneEmailworkplaceMailing cityMailing Stat
12312345123@1233.detestNew YorkNew York
abc45678abc@ab.detestNew YorkNew York
def78019def@def.detestNew YorkNew York

期望转换后的结构

idAttributeValueMailing cityMailing sat
123Phone12345New YorkNew York
123Email123@1233.deNew YorkNew York
123workplacetestNew YorkNew York
abcPhone45678New YorkNew York
abcEmailabc@ab.deNew YorkNew York
abcworkplacetestNew YorkNew York

实现代码

用Pandas内置的melt函数就能快速完成这个转换,代码如下:

# 执行宽转长转换
result_df = df.melt(
    id_vars=['Id', 'Mailing city', 'Mailing Stat'],  # 保留不参与转换的列
    value_vars=['Phone', 'Email', 'workplace'],      # 需要转为键值对的列
    var_name='Attribute',                            # 转换后的属性列名
    value_name='Value'                               # 转换后的属性值列名
)

# 调整列名匹配期望格式
result_df = result_df.rename(columns={
    'Id': 'id',
    'Mailing Stat': 'Mailing sat'
})

# 重置索引(可选操作)
result_df = result_df.reset_index(drop=True)

关键说明

  • melt是Pandas专门处理宽表转长表的工具,核心逻辑是区分「保留列」和「转换列」,自动将转换列拆分为属性-值的配对形式。
  • 最后通过rename调整列名,完全匹配你需要的输出格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 08:50:38