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

请求帮助:将CSV中的嵌套数组拆分至多列

实现CSV数据展开转换需求

问题描述

原始CSV数据:

number,event_date,event_timestamp,event_name,event_params
0,20220315,1668314165054758,eventTracking,"[{'key': 'test0', 'value': {'string_value': None, 'int_value': 1665374225, 'float_value': None, 'double_value': None}}
 {'key': 'test1', 'value': {'string_value': None, 'int_value': 0, 'float_value': None, 'double_value': None}}
 {'key': 'test2', 'value': {'string_value': 'http:\test.com', 'int_value': None, 'float_value': None, 'double_value': None}}
 {'key': 'test3', 'value': {'string_value': 'A@gmail.com', 'int_value': None, 'float_value': None, 'double_value': None}}
 {'key': 'test4', 'value': {'string_value': None, 'int_value': 5, 'float_value': None, 'double_value': None}}]"

期望转换后的CSV格式:

number,event_date,event_timestamp,event_name1,event_params1
0,20220315,1668314165054758,test0,None
0,20220315,1668314165054758,test1,None
0,20220315,1668314165054758,test2,http:\test.com
0,20220315,1668314165054758,test3,A@gmail.com
0,20220315,1668314165054758,test4,None

解决方案

使用Python编写脚本处理,步骤包括读取原始CSV、解析嵌套参数、生成新行并写入输出文件:

import csv
import ast

def transform_csv(input_file, output_file):
    with open(input_file, 'r', newline='', encoding='utf-8') as infile:
        reader = csv.DictReader(infile)
        fieldnames = ['number', 'event_date', 'event_timestamp', 'event_name1', 'event_params1']
        
        with open(output_file, 'w', newline='', encoding='utf-8') as outfile:
            writer = csv.DictWriter(outfile, fieldnames=fieldnames)
            writer.writeheader()
            
            for row in reader:
                # 清理参数字符串中的换行和多余引号,确保能被解析
                params_clean = row['event_params'].replace('\n', '').strip('"')
                params_list = ast.literal_eval(params_clean)
                
                for param in params_list:
                    key = param['key']
                    value_dict = param['value']
                    # 提取第一个非空的参数值
                    param_value = next((v for v in value_dict.values() if v is not None), 'None')
                    
                    writer.writerow({
                        'number': row['number'],
                        'event_date': row['event_date'],
                        'event_timestamp': row['event_timestamp'],
                        'event_name1': key,
                        'event_params1': param_value
                    })

# 替换为你的输入输出文件路径
transform_csv('input.csv', 'output.csv')

代码说明

  1. CSV读写:使用csv.DictReader和csv.DictWriter处理CSV文件,方便按字段名操作数据。
  2. 参数解析:用ast.literal_eval解析Python风格的字典列表字符串(避免json模块无法处理单引号的问题),先清理字符串中的换行符和外层引号。
  3. 值提取:遍历参数值字典,取第一个非None的数值或字符串,若全为None则写入'None'。
  4. 生成新行:每解析一个参数,就复制原始行的基础字段,加上参数的key和值,写入输出文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 04:05:25