如何用Python Polars将LazyFrame收集后写入Gzip压缩CSV文件?
Python Polars 写入Gzip压缩CSV的最优方式
Polars 内置了对压缩格式的直接支持,无需手动借助gzip模块,这是更简洁且性能更优的实现方式。以下是具体用法:
一、DataFrame 写入Gzip压缩CSV
直接调用write_csv方法并指定compression='gzip'参数即可,代码更简洁,且Polars内部会优化压缩逻辑:
import polars as pl # 创建示例DataFrame df = pl.DataFrame({ "foo": [1, 2, 3, 4, 5], "bar": [6, 7, 8, 9, 10], "ham": ["a", "b", "c", "d", "e"] }) # 写入Gzip压缩CSV file_path = 'compressed_dataframe.gz' df.write_csv(file_path, compression='gzip')
二、LazyFrame 写入Gzip压缩CSV
针对LazyFrame,有两种常用方式,其中流式写入的方式更适合大数据集:
方式1:collect后写入
如果需要先执行LazyFrame的计算再写入,可以先collect()转为DataFrame,再用上述方法:
import polars as pl # 创建示例LazyFrame lf = pl.LazyFrame({ "foo": [1, 2, 3, 4, 5], "bar": [6, 7, 8, 9, 10], "ham": ["a", "b", "c", "d", "e"] }) # collect后写入Gzip压缩CSV lf.collect().write_csv('compressed_lazyframe.gz', compression='gzip')
方式2:使用sink_csv流式写入(推荐)
对于超大数据集,推荐使用sink_csv,无需将全量数据加载到内存,直接流式写入压缩文件:
# 流式写入Gzip压缩CSV,无需collect到内存 lf.sink_csv('compressed_lazyframe_sink.gz', compression='gzip')
内容的提问来源于stack exchange,提问作者Isaacnfairplay
相关产品推荐
相关产品推荐

