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

如何用Python将CSV文件中的多个独立表格合并为单个表格?

Python合并CSV多表格并完成数据迁移方案

一、先解决目标文件的多表格识别与读取

CSV里的独立表格一般以空行分隔,直接用pandas读取时可以先按行拆分出各表格的行数据,再分别解析:

import pandas as pd

def split_csv_tables(file_path):
    tables = []
    current_table = []
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            stripped_line = line.strip()
            # 空行作为表格分隔符
            if not stripped_line:
                if current_table:
                    df = pd.read_csv(pd.io.common.StringIO('\n'.join(current_table)))
                    tables.append(df)
                    current_table = []
            else:
                current_table.append(stripped_line)
        # 处理最后一个未被空行收尾的表格
        if current_table:
            df = pd.read_csv(pd.io.common.StringIO('\n'.join(current_table)))
            tables.append(df)
    return tables

二、多表格重组与合并

针对长度各异的表格,先统一列集合(缺失列补NaN),再拼接成单个表格:

def merge_tables(tables):
    # 收集所有表格的列名
    all_columns = set()
    for df in tables:
        all_columns.update(df.columns)
    all_columns = list(all_columns)
    
    # 对齐每个表格的列
    aligned_tables = []
    for df in tables:
        aligned_df = df.reindex(columns=all_columns)
        aligned_tables.append(aligned_df)
    
    # 合并所有表格
    merged_df = pd.concat(aligned_tables, ignore_index=True)
    return merged_df

三、高效变量重命名、筛选与格式转换

  1. 变量重命名:用rename()批量处理,比单独用as更灵活高效
# 定义原列名到目标列名的映射
rename_mapping = {
    'old_col1': 'new_col1',
    'old_col2': 'new_col2'
}
merged_df.rename(columns=rename_mapping, inplace=True)
  1. 特定变量筛选:直接指定列名或按条件筛选
# 保留需要的列
target_columns = ['new_col1', 'new_col2', 'required_col']
filtered_df = merged_df[target_columns]

# 按条件筛选行(例如筛选score大于60的数据)
filtered_df = merged_df[merged_df['new_col2'] > 60]
  1. 格式转换:常规类型用astype(),复杂转换用pd.to_datetime()或apply()
# 转换列类型为浮点数
filtered_df['new_col2'] = filtered_df['new_col2'].astype(float)

# 日期字符串转datetime类型
filtered_df['date_col'] = pd.to_datetime(filtered_df['date_col'], format='%Y-%m-%d')

四、完整流程示例

# 1. 读取并拆分源CSV中的多表格
tables = split_csv_tables('source.csv')
# 2. 合并为单个表格
merged_df = merge_tables(tables)
# 3. 重命名、筛选、格式转换
rename_mapping = {'old_user_id': 'user_id', 'old_score': 'score'}
merged_df.rename(columns=rename_mapping, inplace=True)
filtered_df = merged_df[['user_id', 'score', 'register_date']]
filtered_df['score'] = filtered_df['score'].astype(float)
filtered_df['register_date'] = pd.to_datetime(filtered_df['register_date'])
# 4. 保存到目标文件
filtered_df.to_csv('target.csv', index=False, encoding='utf-8')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 17:57:09