python横向合并多个csv

您所在的位置:网站首页 pandas纵向合并两个csv文件 python横向合并多个csv

python横向合并多个csv

2024-06-10 07:52| 来源: 网络整理| 查看: 265

最近数据合并工作较多,手动合并太费时费力了,再来一波工具。

1、源数据如下:

源数据1

源数据2

共4个简单测试数据,想想下几十上百张这种excel,每个excel表中几千上万条数据的合并....

2、程序合并代码

运行须安装pandas,我的文件放于项目下的csvunion目录中:

import glob

import os

import pandas as pd

inputfile = str(os.path.dirname(os.getcwd())) + "\myTools"+"\csvunion\*.csv"

outputfile = str(os.path.dirname(os.getcwd()))+ "\myTools"+"\csvunion\\testall.csv"

csv_list = glob.glob(inputfile)

filepath = csv_list [0]

df = pd.read_csv(filepath,encoding="gbk",low_memory=False)

df = df.to_csv(outputfile,encoding="gbk",index=False)

for i in range(1,len(csv_list)):

filepath = csv_list [i]

df = pd.read_csv(filepath,encoding="gbk",low_memory=False)

df = df.to_csv(outputfile,encoding="gbk",index=False,header=False,mode='a+')

image.gif

3、运行结果

合并结果

嗯,秒出结果。

我处理的数据是近500个csv文件,每个csv文件中有8万多条数据,这个方法真的是拯救了我。发出来共享一下。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3