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

如何横向合并多个CSV文件 避免pandas按逗号拆分导致列拆分错误

方案1:直接修正Pandas用法(最简便)

原来的错误在于手动对整行字符串做逗号拆分,忽略了CSV标准里引号包裹的内容属于单个字段的规则,pandas.read_csv本身就自带对CSV格式的正确解析能力,不需要手动拆分:

import os
import glob
import pandas as pd

dirname = r'你的CSV文件夹路径'
extension = 'csv'
# 自动拼接路径避免错误
all_filenames = glob.glob(os.path.join(dirname, f'*.{extension}'))

dflist = []
for file in all_filenames:
    # pandas自动解析CSV格式,正确识别引号包裹的逗号为字段内容
    df = pd.read_csv(file, header=None)
    dflist.append(df)

# 横向拼接,行数不一致时自动补空值
result = pd.concat(dflist, axis=1)
# 输出时保留CSV格式规则,不会破坏原有字段结构
result.to_csv(r'输出文件路径.csv', index=False, header=False)

如果读取或写入出现乱码,可在read_csv和to_csv方法里添加参数encoding='gbk'适配Windows系统生成的CSV文件。

方案2:修改你已有的纵向合并代码实现(纯文本读写,无需依赖pandas)

全程不对CSV行内容做拆分,仅按行对齐拼接,完全不会破坏原有字段格式:

import os

Dir = r'你的CSV文件夹路径'
file_name = 'mergedcsvfilename'
# 先缓存所有CSV的行内容
all_csv_lines = []
max_line_num = 0

for file in os.listdir(Dir):
    if '.DS_Store' in file or not file.endswith('.csv'):
        continue
    file_path = os.path.join(Dir, file)
    with open(file_path, 'r', encoding='utf-8') as rf:
        # 读取当前CSV所有行,去除末尾换行符
        lines = [line.rstrip('\n') for line in rf if line.strip()]
        all_csv_lines.append(lines)
        if len(lines) > max_line_num:
            max_line_num = len(lines)

# 按行对齐横向拼接
with open(f'{file_name}.csv', 'w', encoding='utf-8') as wf:
    for line_idx in range(max_line_num):
        current_line_parts = []
        for single_csv_lines in all_csv_lines:
            # 行数不够的CSV补空内容
            part = single_csv_lines[line_idx] if line_idx < len(single_csv_lines) else ''
            current_line_parts.append(part)
        wf.write(','.join(current_line_parts) + '\n')

如果出现乱码,可将代码中encoding='utf-8'替换为encoding='gbk'。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 17:27:02