You need to enable JavaScript to run this app. 如何使用Python或C#将宽格式CSV转换为指定结构的长格式表格
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python或C#将宽格式CSV转换为指定结构的长格式表格

CSV宽表转长格式实现方案

Python 实现

利用pandas内置的宽转长能力可以最快完成转换,核心逻辑步骤:

  • 读取原始宽表CSV文件
  • 调用melt方法指定保留列、新生成的列名,自动完成格式拆解
  • 将结果导出为符合要求的长格式CSV

对应实现代码:

import pandas as pd

# 读取原始宽表
df = pd.read_csv("原始数据.csv")

# 宽转长:保留respondant_id列,剩余列名映射为internal_location,列值映射为ccp
df_long = df.melt(
    id_vars="respondant_id",
    var_name="internal_location",
    value_name="ccp"
)

# 导出结果,不写入行索引
df_long.to_csv("转换结果.csv", index=False)

运行后生成的表格会自动匹配需求的6行数据:

  • respondant_id为X的3行,internal_location分别为10410、10411、10412,对应ccp值P12、P13、P14
  • respondant_id为Y的3行,internal_location分别为10410、10411、10412,对应ccp值P18、P19、P147

C# 实现

借助CsvHelper库处理CSV读写,通过逐行拆解宽表字段生成长表条目,核心逻辑步骤:

  • 定义原始宽表、目标长表对应的实体类
  • 读取原始CSV的宽表记录,逐行遍历除respondant_id外的所有字段,拼接为长表条目
  • 将所有长表条目写入新的CSV文件

对应实现代码:

using CsvHelper;
using CsvHelper.Configuration;
using System.Globalization;
using System.IO;
using System.Collections.Generic;

// 原始宽表实体
public class WideRecord
{
    public string respondant_id { get; set; }
    public string _10410 { get; set; }
    public string _10411 { get; set; }
    public string _10412 { get; set; }
}

// 目标长表实体
public class LongRecord
{
    public string respondant_id { get; set; }
    public string internal_location { get; set; }
    public string ccp { get; set; }
}

// 转换执行
var csvConfig = new CsvConfiguration(CultureInfo.InvariantCulture)
{
    HasHeaderRecord = true
};
var longResult = new List<LongRecord>();

using (var streamReader = new StreamReader("原始数据.csv"))
using (var csvReader = new CsvReader(streamReader, csvConfig))
{
    var wideData = csvReader.GetRecords<WideRecord>();
    foreach (var row in wideData)
    {
        longResult.Add(new LongRecord { 
            respondant_id = row.respondant_id, 
            internal_location = "10410", 
            ccp = row._10410 
        });
        longResult.Add(new LongRecord { 
            respondant_id = row.respondant_id, 
            internal_location = "10411", 
            ccp = row._10411 
        });
        longResult.Add(new LongRecord { 
            respondant_id = row.respondant_id, 
            internal_location = "10412", 
            ccp = row._10412 
        });
    }
}

// 写入结果文件
using (var streamWriter = new StreamWriter("转换结果.csv"))
using (var csvWriter = new CsvWriter(streamWriter, csvConfig))
{
    csvWriter.WriteRecords(longResult);
}

如果后续原始表新增了更多类似的数值列,不需要修改实体硬编码,直接读取表头动态遍历即可适配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 14:45:03