合并具有相同列的excel文件(行连接)

合并具有相同列的excel文件(行连接),第1张

文章目录
  • 前言
  • 一、代码
  • 二、使用
  • 总结


前言

需解决的问题:合并多个具有相同列的excel文件
解决思路:pandas.concat()

pandas.concat(objs, axis=0, join='outer', ignore_index=False, keys=None, levels=None, names=None, verify_integrity=False, sort=False, copy=True)
# Concatenate pandas objects along a particular axis with optional set logic along the other axes.

pandas.concat()通常用来连接DataFrame对象。默认情况下axis=0,即对两个或多个DataFrame对象进行纵向连接;axis=1时则实现DataFrame对象的横向连接。

一、代码
import pandas as pd
import os


def con_excels(ori_dir, save_dir, new_filename, fields=""):
    """
    合并同一文件夹下的excel文件
    :param ori_dir: 需合并excel文件夹路径
    :param save_dir: 合并后保存路径
    :param new_filename: 新的excel文件名称
    :param fields: 去重所依据的字段
    :return: 
    """
    file_list = os.listdir(ori_dir)  # 找到文件路径下的所有表格名称,返回列表
    new_list = []

    for file in file_list:
        file_path = os.path.join(ori_dir,file)    # 重构文件路径
        dataframe = pd.read_excel(file_path)    # 将excel转换成DataFrame
        new_list.append(dataframe)  # 保存到新列表中

    df = pd.concat(new_list)  # 多个DataFrame合并为一个
    if fields:
        df.drop_duplicates(keep='first', subset=fields, inplace=True)  # 根据fields去重

    df.drop_duplicates(keep='first', inplace=True)  # 去重
    if not os.path.exists(save_dir):
        os.mkdir(save_dir)
    writer = pd.ExcelWriter(os.path.join(save_dir, new_filename), engine='xlsxwriter',options={'strings_to_urls': False})
    df.to_excel(writer,index=False)
    writer.save()
    print("合并完成")
二、使用
if __name__ == "__main__":
    file_dir = r"split_result"  # 需合并excel文件夹路径
    save_dir = r"con_files"  # 合并后保存路径
    new_filename = 'concat_excel.xlsx'  # 新的表格名称  
    con_excels(file_dir, save_dir, new_filename)
    
    # fields = ["文章标题", "文章内容"]
    # con_excels(file_dir, save_dir, new_filename, fields=fields)
总结
  1. 合并表格的方式有多种,可尝试使用xlsxwriter模块实现
  2. 可以使用相同的方法实现其他类型数据(可读取为DataFrame对象)的合并
  3. 设置axis=1,实现多个DataFrame对象的列连接

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/788624.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-05
下一篇 2022-05-05

发表评论

登录后才能评论

评论列表(0条)

保存