用 python 很好地连接 csv 文件

concatenating csv files nicely with python

我的程序首先将一个大数据集聚类成 100 个集群,然后 运行 使用 multiprocessing 在数据集的每个集群上建立一个模型。我的目标是将所有输出值连接到一个大的 csv 文件中,该文件是 100 个拟合模型的所有输出数据的连接。

现在,我只是创建 100 个 csv 文件,然后在包含这些文件的文件夹上循环并将它们逐行复制到一个大文件中。

我的问题:有没有更聪明的方法来获得这么大的输出文件而无需导出 100 个文件。我使用 pandasscikit-learn 进行数据处理,multiprocessing 进行并行化。

如果您所有的部分 csv 文件都没有 headers 并且共享列号和顺序,您可以像这样连接它们:

with open("unified.csv", "w") as unified_csv_file:
    for partial_csv_name in partial_csv_names:
        with open(partial_csv_name) as partial_csv_file:
            unified_csv_file.write(partial_csv_file.read())

让你的处理线程 return 将数据集发送到主进程,而不是自己编写 csv 文件,然后当它们将数据返回给你的主进程时,让它将它们写入一个连续的 csv。

from multiprocessing import Process, Manager

def worker_func(proc_id,results):

    # Do your thing

    results[proc_id] = ["your dataset from %s" % proc_id]

def convert_dataset_to_csv(dataset):

    # Placeholder example.  I realize what its doing is ridiculous

    converted_dataset = [ ','.join(data.split()) for data in dataset]
    return  converted_dataset

m = Manager()
d_results= m.dict()

worker_count = 100

jobs = [Process(target=worker_func,
        args=(proc_id,d_results))
        for proc_id in range(worker_count)]

for j in jobs:
    j.start()

for j in jobs:
    j.join()


with open('somecsv.csv','w') as f:

    for d in d_results.values():

        # if the actual conversion function benefits from multiprocessing,
        # you can do that there too instead of here

        for r in convert_dataset_to_csv(d):
            f.write(r + '\n')

http://computer-programming-forum.com/56-python/b7650ebd401d958c.htm 中摘取了它的内脏,它是 gem。

#!/usr/bin/python
# -*- coding: utf-8 -*-
from glob import glob
n=1
file_list = glob('/home/rolf/*.csv')
concat_file = open('concatenated.csv','w')
files = map(lambda f: open(f, 'r').read, file_list)
print "There are {x} files to be concatenated".format(x=len(files))    
for f in files:
    print "files added {n}".format(n=n)
    concat_file.write(f())
    n+=1
concat_file.close()