使用 Polars 并行读取压缩的 CSV

问题描述 投票:0回答:1

假设我有一个

.csv.xz
文件列表,我想并行读取它们。

我知道我可以使用生成器表达式依次执行此操作:

import glob
import lzma
import polars as pl

the_path = 'paths/to/my/*.csv.xz'
all_dfs = pl.concat(
    (pl.read_csv(lzma.open(i)) for i in sorted(glob(the_path))), 
    how='vertical')

但我也意识到并行阅读它们的可能性(?):https://docs.pola.rs/user-guide/io/multiple/#reading-and-processing-in-parallel。阅读

pl.scan_csv
的方法签名,似乎这只能通过
Path
List[Path]
实现。鉴于似乎还没有任何压缩推断(相反
pd.read_csv('file.csv.xz')
)这是否意味着我对压缩的 CSV 很满意?

或者,是否可以并行执行 IO,而不使用

joblib
concurrent.futures
之类的东西?

python-polars
1个回答
0
投票

您可以使用并发.futures 来做到这一点:

import glob
import lzma
import polars as pl
import concurrent.futures

def read_data(file):
    print(f"Reading file: {file}")
    return pl.read_csv(lzma.open(file))

the_path = '/content/*.csv.xz'
files = sorted(glob.glob(the_path))

executor = concurrent.futures.ThreadPoolExecutor(max_workers=5)

all_dfs = pl.concat(executor.map(read_data, files), how='vertical')
© www.soinside.com 2019 - 2024. All rights reserved.