高效地追加CSV文件python

d5vmydt9  于 12个月前  发布在  Python
关注(0)|答案(1)|浏览(109)

我尝试在Python中追加> 1000个csv文件(所有文件都具有相同的格式)。文件大小在1KB到30GB之间。所有文件总共有200GB。我想把这些文件合并成一个唯一的 Dataframe 。下面是我正在做的事情,非常非常慢:

folder_path = 'Some path here'
csv_files = [file for file in os.listdir(folder_path) if file.endswith('.csv')]
combined_data = pd.DataFrame()
for e, csv_file in enumerate(csv_files): 
    print(f'Processing {e+1} out of {len(csv_files)}: {csv_file}')
    combined_data = pd.concat([combined_data, pd.read_csv(os.path.join(folder_path, csv_file), dtype={'stringbvariablename': str})])

其中一个变量是字符串。其他的都是数字。RAM内存不是问题,因为我使用的是集群。

lvmkulzt

lvmkulzt1#

如果你所有的文件都是相同的格式,而你只是想创建一个新的CSV,那么就不要使用pandas。

import csv
import pathlib

def write_to_writer(writer: csv.writer, path: pathlib.Path, skipheader=False) -> None:
    with path.open(newline="") as f:
        reader = csv.reader(f)
        if skipheader:
            next(reader)
        writer.writerows(reader)

folder_path = pathlib.Path('Some path here')
csv_files = [p for p in folder_path.iterdir() if p.suffix =='.csv']

with open('combined_data.csv', 'w', newline="") as fout:
    writer = csv.writer(fout)
    # handle first csv, with header
    first_path, *rest = csv_paths
    write_to_writer(writer, first_path, skipheader=False)
    for path in rest:
        write_to_writer(writer, path, skipheader=True)

这避免了循环中的pd.concat问题,即classic antipattern
然而,如果你需要一个大的数据框(因为你要实际使用数据框),那么你的问题只需要添加到一个列表中,然后在最后进行协调即可解决:

import pathlib

import pandas as pd

folder_path = pathlib.Path('Some path here')
csv_paths = [p for p in folder_path.iterdir() if p.suffix =='.csv']

df = pd.concat([
    pd.read_csv(path, dtype={'stringbvariablename': str})
    for path in csv_paths
])

同样,这避免了反模式(因为.append在循环中执行到列表 * 是高效的 *)

相关问题