Skip to main content
 首页 » 编程设计

python之如何根据列名将多个 csv 文件连接成一个,而不必在代码中键入每个列标题

2024年12月31日9lonelyxmas

我是 python 的新手(大约一周的经验),我似乎找不到问题的答案。

我正在尝试将基于我的文件夹 Data 中的数百个 csv 文件合并到一个基于列名的 csv 文件中。

我找到的解决方案要求我输入每个文件名或列标题,这需要几天时间。

我使用这段代码创建了一个 csv 文件,但列名四处移动,因此数据在整个 DataFrame 中不在同一列中:

import pandas as pd 
import glob 
import os 
def concatenate(indir=r"C:\\Users\ge\Documents\d\de",  
outfile = r"C:\Users\ge\Documents\d"): 
    os.chdir(indir) 
    fileList=glob.glob("*.csv") 
    dfList = [] 
    for filename in fileList: 
        print(filename) 
        df = pd.read_csv(filename, header = None) 
        dfList.append(df) 
        concatDf = pd.concat(dfList, axis = 0) 
    concatDf.to_csv(outfile, index= None) 

因为我只有不到一周的时间在数据集上运行统计数据,所以有快速射击的方法吗?

如有任何帮助,我们将不胜感激。

请您参考如下方法:

这是一种内存高效的方法。

from pathlib import Path 
import csv 
 
indir = Path(r'C:\\Users\gerardchurch\Documents\Data\dev_en') 
outfile = Path(r"C:\\Users\gerardchurch\Documents\Data\output.csv") 
 
 
def find_header_from_all_files(indir): 
    columns = set() 
    print("Looking for column names in", indir) 
    for f in indir.glob('*.csv'): 
        with f.open() as sample_csv: 
            sample_reader = csv.DictReader(sample_csv) 
            try: 
                first_row = next(sample_reader) 
            except StopIteration: 
                print("File {} doesn't contain any data. Double check this".format(f)) 
                continue 
            else: 
                columns.update(first_row.keys()) 
    return columns 
 
 
columns = find_header_from_all_files(indir) 
print("The columns are:", sorted(columns)) 
 
with outfile.open('w') as outf: 
    wr = csv.DictWriter(outf, fieldnames=list(columns)) 
    wr.writeheader() 
    for inpath in indir.glob('*.csv'): 
        print("Parsing", inpath) 
        with inpath.open() as infile: 
            reader = csv.DictReader(infile) 
            wr.writerows(reader) 
print("Done, find the output at", outfile) 

当其中一个输入 csvs 不包含所有列

时,这应该处理这种情况