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

如何从DataFrame列名字符串生成新列并转换数据格式?

Pandas实现宽表转长表:从列名提取信息生成新列

输入DataFrame

A Jan.S1 Jan.S2 Feb.S1 Feb.S2
x 1      2      3      4
y 6      7      8      9

期望输出DataFrame

A  month S1 S2 
x  Jan   1  2
x  Feb   3  4
y  Jan   6  7
y  Feb   8  9

解决方案

这里提供两种Pandas实现方式,根据场景灵活选择:


方法一:用wide_to_long(最简洁,适配固定格式列名)

wide_to_long是Pandas专门为前缀.后缀格式的宽表设计的工具,一步完成转换:

import pandas as pd

# 构造输入数据
df = pd.DataFrame({
    'A': ['x', 'y'],
    'Jan.S1': [1, 6],
    'Jan.S2': [2, 7],
    'Feb.S1': [3, 8],
    'Feb.S2': [4, 9]
})

# 核心转换逻辑
result = pd.wide_to_long(
    df,
    stubnames=['S1', 'S2'],  # 列名中固定的后缀部分
    i='A',                   # 保留的主键列
    j='month',               # 从列名提取的新列(前缀:Jan/Feb)
    sep='.',                 # 列名的分隔符
    suffix='\\w+'            # 匹配前缀的正则规则
).reset_index()

# 调整列顺序与期望输出一致
result = result[['A', 'month', 'S1', 'S2']]
print(result)

输出结果:

A month  S1  S2
0  x   Jan   1   2
1  x   Feb   3   4
2  y   Jan   6   7
3  y   Feb   8   9

方法二:用melt+split+pivot(更灵活,适配复杂列名)

如果列名格式不固定,或者需要自定义处理逻辑,用这套组合拳更合适:

import pandas as pd

df = pd.DataFrame({
    'A': ['x', 'y'],
    'Jan.S1': [1, 6],
    'Jan.S2': [2, 7],
    'Feb.S1': [3, 8],
    'Feb.S2': [4, 9]
})

# 1. 宽表转窄表,保留A列,其他列合并为col和value
melted = df.melt(id_vars='A', var_name='col', value_name='value')
# 2. 拆分col列为month和type(S1/S2)
melted[['month', 'type']] = melted['col'].str.split('.', expand=True)
# 3. 把type转成列,恢复目标结构
result = melted.pivot(index=['A', 'month'], columns='type', values='value').reset_index()
# 4. 清理列名索引,调整列顺序
result.columns.name = None
result = result[['A', 'month', 'S1', 'S2']]
print(result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 01:15:41