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

pandas如何将CSV多列按对应关系拆分为多行

pandas实现多列配对宽转长方法

这个需求是将同序号的错误码、CID列配对后拆分为多行,属于典型的宽表转长表场景,可按以下步骤实现:

  • 导入pandas库,加载原始数据集
  • 调整列名格式适配宽转长函数规则
  • 执行宽转长操作后整理列名、列顺序,得到目标结果

完整可运行代码如下:

import pandas as pd

# 构造原始示例数据,从本地文件读取可替换为pd.read_excel/pd.read_csv等读取方法
df = pd.DataFrame({
    'Version': ['1.0.0'],
    'ID': [555],
    'Col1_ErrorCode': [1111],
    'Col2_ErrorCode': [2222],
    'Col3_ErrorCode': [3333],
    'Col1_CID': ['AAA'],
    'Col2_CID': ['BBB'],
    'Col3_CID': ['CCC']
})

# 调整列名:提取列序号移到列名末尾,适配wide_to_long识别规则
df.columns = [
    f"{col.split('_')[1]}_{col.split('_')[0].replace('Col', '')}"
    if col.startswith('Col') and '_' in col
    else col
    for col in df.columns
]

# 执行宽转长:固定Version、ID为标识列,按序号配对ErrorCode和CID
result = pd.wide_to_long(
    df,
    stubnames=['ErrorCode', 'CID'],
    i=['Version', 'ID'],
    j='serial_num',
    sep='_'
).reset_index(drop=True)

# 整理列名和顺序,匹配目标输出格式
result = result.rename(columns={'ErrorCode': 'Error'})[['Version', 'ID', 'Error', 'CID']]

运行后得到的结果完全符合预期:

Version   ID  Error  CID
0   1.0.0  555   1111  AAA
1   1.0.0  555   2222  BBB
2   1.0.0  555   3333  CCC

说明:如果后续新增Col4、Col5等配对列,只要列名保持ColN_ErrorCode/ColN_CID的命名规则,上述代码无需修改即可自动适配,不需要手动调整列映射关系。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 00:54:44