You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Polars是否有等效于pandas.to_csv()无文件名返回字符串的方法?

在Polars中实现类似Pandas无路径to_csv()的字符串输出方法

Polars提供了无需转换为Pandas DataFrame就能生成CSV字符串的方案,核心是借助io.StringIO内存缓冲区捕获write_csv()的输出:

生成制表符分隔的字符串

直接通过内存缓冲区捕获输出,示例代码:

import polars as pl
from io import StringIO

# 示例Polars DataFrame
polarsdf = pl.DataFrame({"col1": [1, 2, 3], "col2": ["a", "b", "c"]})

# 生成制表符分隔的CSV字符串
buffer = StringIO()
polarsdf.write_csv(buffer, sep="\t", include_header=True)
csv_str = buffer.getvalue().strip()  # 去除末尾多余换行符

适配Shiny for Python的下载功能

针对你的下载需求,直接用Polars原生方法实现即可,无需转换为Pandas:

from io import StringIO
import polars as pl

def download_something():
    buffer = StringIO()
    polarsdf.write_csv(buffer, sep="\t", include_header=True)
    yield buffer.getvalue().strip()

如果不需要额外处理字符串,也可以直接返回缓冲区内容,上述逻辑和你当前的实现完全匹配,且避免了Pandas转换的开销。

内容的提问来源于stack exchange,提问作者gernophil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 00:59:52