首页 > 解决方案 > 优化 os.walk() 迭代;在 64 位、4 核、64 GB、2.50GHz 系统上

问题描述

我有一个 64 位、4 核、2.50GHz、64GB 系统和 13GB 可用内存。我正在尝试使用以下代码读取 24 个 csv 约 4000 万行;

def test():
    test = pd.DataFrame()
    rootdir ='/XYZ/A'
    for subdir, dirs, files in os.walk(rootdir):
        for file in files:
            df = pd.read_csv(os.path.join(subdir, file), low_memory=False)
            test = pd.concat([test, df])
    return test

我怎样才能优化它以更快地运行,而不会导致内核死亡。我应该在 Pyspark 中实现这个吗???如果我错过任何细节,请告诉我。

标签: pythonpandas

解决方案


试一试,我使用了pathlib模块,因为它提供了更简洁和更清晰的代码恕我直言,并且您可以利用迭代器和生成器表达式:

from pathlib import Path
def test():
    rootdir ='/XYZ/A'
    #assumption is that they are all csvs
    #if not. u could just use rglob('*.*')
    #this will recursively search through the directory
    #and pull all files with the extension csv
    #or all files if u use ('*.*')
    #which might be a bit more intensive computation
    all_files = Path(rootdir).rglob('*.csv')
    all_dfs = (pd.read_csv(f)
               #kindly test this aspect and c
               #stem gets u the name before '.csv'
               #and returns a string
               #rsplit splits based on the last '_'
               .assign(Date = f.stem.rsplit('_')[-1])
               for f in all_files)
    #trying to delay the intense computation till it gets here
    #hence the use of generator expressions
    final_df = pd.concat(all_dfs,ignore_index=True)
    return final_df

让我们知道它是怎么回事;如果它失败了,我会把它取下来,以免混淆其他人。


推荐阅读