我正在尝试将
str
列从 str
转换为 float
(它旨在成为浮点数)。但是,该字符串有逗号和点,我无法正确替换这些值:
import polars as pl
df = pl.DataFrame({"numbers": ["1.004,00", "2.005,00", "3.006,00"]})
df = df.with_column(
df["numbers"].str.replace(".", "").str.replace(",", ".").cast(pl.Float64)
)
print(df)
我得到:
计算错误:在“数字”列中从 str 到 f64 的转换失败 对于 3 个值中的 3 个:[".004.00", ".005.00", ".006.00"]
我也尝试删除“。”不使用任何东西:
df = df.with_columns(df["numbers"].str.replace(".", ""))
print(df)
但是我得到的值没有第一个数字。
str.replace
使用正则表达式,因此点与第一个字符匹配。逃避它:
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("\.", "").str.replace(",", ".").cast(pl.Float64)
)
)
print(df)
输出:
shape: (3, 1)
┌─────────┐
│ numbers │
│ --- │
│ f64 │
╞═════════╡
│ 1004.0 │
│ 2005.0 │
│ 3006.0 │
└─────────┘