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

如何在Polars DataFrame中用格式说明符转换数值列为字符串?

解决Polars中使用格式说明符格式化数值列的问题

你遇到的ValueError是因为旧版本Polars的pl.format函数对带格式说明符的占位符支持有限,或者写法需要调整。以下是两种可行的解决方法:

方法一:使用map_elements调用Python原生格式化

直接利用Python的字符串格式化能力,通过map_elements对列中的每个元素进行处理:

import polars as pl
df = pl.DataFrame({'size': [34.2399, 1232.22, -479.1]})
df = df.with_columns(
    pl.col('size').map_elements(lambda x: "{:,.2f}".format(x), return_dtype=pl.String).alias('formatted_size')
)

运行后输出:

shape: (3, 2)
┌───────────┬────────────────┐
│ size      ┆ formatted_size │
│ ---       ┆ ---            │
│ f64       ┆ str            │
╞═══════════╪════════════════╡
│ 34.2399   ┆ 34.24          │
│ 1232.22   ┆ 1,232.22       │
│ -479.1    ┆ -479.10        │
└───────────┴────────────────┘

方法二:升级Polars后使用新版pl.format

如果你的Polars版本低于0.17.0,升级到新版本后,pl.format已经支持在占位符中直接使用格式说明符,原代码可直接运行:

import polars as pl
df = pl.DataFrame({'size': [34.2399, 1232.22, -479.1]})
df = df.with_columns(
    pl.format("{:,.2f}", pl.col('size')).alias('formatted_size')
)

新版本会正确识别格式说明符,无需额外处理。

内容的提问来源于stack exchange,提问作者Phil-ZXX

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 19:33:11