将多个文件读入dask数据帧

2024-05-12 16:14:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将多个csv文件读入一个dask数据帧。由于某些原因,我的部分原始数据丢失(不知道为什么?!)。我想知道什么是将它们全部读入dask的最佳方法?我使用了for循环,但不确定它是否正确

 for file in os.listdir(dds_glob):
    if file.endswith('issued_processed.txt'):
        ddf = dd.read_fwf(os.path.join(dds_glob,file),
                          colspecs=cols,
                          header=None,
                          dtype=object,
                          names=names)

或者我应该使用这样的东西:

dfs = delayed(pd.read_fwf)('/data/input/*issued_processed.txt',
                           colspecs=cols,
                           header=None,
                           dtype=object,
                           names=names)  
ddf = dd.from_delayed(dfs)

Tags: txtforreadnamesosglobdddask
1条回答
网友
1楼 · 发布于 2024-05-12 16:14:52

至少有两种方法:

  1. dask.dataframe提供一个文件列表,因此使用第一个代码段看起来像:
file_list = [
    os.path.join(dds_glob,file)
    for file os.listdir(dds_glob) if file.endswith('issued_processed.txt')
]

# other options are skipped for convenience
ddf = dd.read_fwf(file_list)
  1. delayed对象构造数据帧,使用第二个代码段将如下所示:
# other options are skipped, but can be included after the `file`
dfs = [delayed(pd.read_fwf)(file) for file in file_list] 
ddf = dd.from_delayed(dfs)

第一种方法可以解决大约82%的用例,但对于其他情况,您可能需要尝试第二种方法或更复杂的方法

相关问题 更多 >