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

Polars中如何替换字符串的点与逗号以转换为float类型?

问题原因

你的代码出错是因为Polars的str.replace()默认使用正则表达式模式,其中.是匹配任意单个字符的通配符,而非普通的小数点。所以str.replace(".", "")会把每个字符串的第一个字符(比如"1.004,00"里的"1")替换为空,导致后续处理后得到无效的浮点数字符串,最终转换失败。

解决方案

解决核心是让replace()把.当作普通字符处理,有两种可行方式:

方式1:使用literal=True参数

显式指定替换操作按字面量匹配,不启用正则模式:

import polars as pl

df = pl.DataFrame({"numbers": ["1.004,00", "2.005,00", "3.006,00"]})
df = df.with_columns(
    pl.col("numbers")
    .str.replace(".", "", literal=True)  # 字面量匹配并删除千分位的点
    .str.replace(",", ".", literal=True)  # 把逗号替换为小数点
    .cast(pl.Float64)
    .alias("numbers")
)
print(df)

方式2:正则转义.

用正则转义符\把.转义为普通字符:

df = df.with_columns(
    pl.col("numbers")
    .str.replace(r"\.", "")  # 转义后匹配真正的小数点
    .str.replace(",", ".")
    .cast(pl.Float64)
    .alias("numbers")
)
执行结果

处理后DataFrame会输出:

shape: (3, 1)
┌─────────┐
│ numbers │
│ ---     │
│ f64     │
╞═════════╡
│ 1004.0  │
│ 2005.0  │
│ 3006.0  │
└─────────┘

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 10:23:13