如何对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]})
显示结果如下:
| day | category | min_feature1 | max_feature1 | min_feature2 | max_feature2 |
|---|---|---|---|---|---|
| 1 | a | 1 | 8 | 2 | 6 |
| 1 | b | 2 | 9 | 3 | 9 |
| 2 | a | 3 | 10 | 4 | 12 |
| 2 | b | 4 | 11 | 5 | 13 |
希望转换为如下结构:
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'])
显示结果:
| day | category | feature | min | max |
|---|---|---|---|---|
| 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 |
请问该如何实现这一转换?
解决方案
可以通过Pandas的melt+列拆分+pivot组合操作实现,步骤如下:
将宽表转为长表,保留标识列
以day和category为固定标识列,把所有特征相关列转为行数据:melted = df.melt(id_vars=['day', 'category'], var_name='type_feature', value_name='value')拆分特征类型与特征名
把type_feature列(如min_feature1)按下划线拆分为类型(min/max)和特征名:melted[['type', 'feature']] = melted['type_feature'].str.split('_', n=1, expand=True)将类型转为列,重置索引
通过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
相关产品推荐
相关产品推荐

