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

如何对Pandas DataFrame进行类熔解(Melting)转换?

问题描述

我有如下Pandas DataFrame:

import pandas as pd
df = pd.DataFrame({'day': [1, 1, 2, 2], 'category': ['a', 'b', 'a', 'b'],
              'min_feature1': [1, 2, 3, 4], 'max_feature1': [8, 9, 10, 11],
              'min_feature2': [2, 3, 4, 5], 'max_feature2': [6, 9, 12, 13]})

显示结果如下:

daycategorymin_feature1max_feature1min_feature2max_feature2
1a1826
1b2939
2a310412
2b411513

希望转换为如下结构:

result = pd.DataFrame([[1, 'a', 'feature1', 1, 8],
 [1, 'a', 'feature2', 2, 6],
[1, 'b', 'feature1', 2, 9],
[1, 'b', 'feature2', 3, 9],
[2, 'a', 'feature1', 3, 10],
[2, 'a', 'feature2', 4, 12],
[2, 'b', 'feature1', 4, 11],
[2, 'b', 'feature2', 5, 13],], columns=['day', 'category', 'feature', 'min', 'max'])

显示结果:

daycategoryfeatureminmax
1afeature118
1afeature226
1bfeature129
1bfeature239
2afeature1310
2afeature2412
2bfeature1411
2bfeature2513

请问该如何实现这一转换?

解决方案

可以通过Pandas的melt+列拆分+pivot组合操作实现,步骤如下:

  1. 将宽表转为长表,保留标识列
    以day和category为固定标识列,把所有特征相关列转为行数据:

    melted = df.melt(id_vars=['day', 'category'], var_name='type_feature', value_name='value')
    
  2. 拆分特征类型与特征名
    把type_feature列(如min_feature1)按下划线拆分为类型(min/max)和特征名:

    melted[['type', 'feature']] = melted['type_feature'].str.split('_', n=1, expand=True)
    
  3. 将类型转为列,重置索引
    通过pivot把type列的min和max转为独立列,再清理索引:

    result = melted.pivot(index=['day', 'category', 'feature'], columns='type', values='value').reset_index()
    result.columns.name = None  # 移除列索引的冗余名称
    

也可以合并为一行链式操作:

result = (df.melt(id_vars=['day', 'category'], var_name='type_feature')
            .assign(**dict(zip(['type', 'feature'], 
                               zip(*df.melt(id_vars=['day', 'category'])['type_feature'].str.split('_', n=1)))))
            .pivot(index=['day', 'category', 'feature'], columns='type', values='value')
            .reset_index()
            .rename_axis(None, axis=1))

执行上述代码后,即可得到目标结构的DataFrame。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 05:05:03