在转换为pl.String时指定数字的字符串格式

问题描述 投票:0回答:1

是否有任何方法可以指定格式说明符,例如,转换

pl.Float32
,而不需要对句点字符进行复杂的搜索?就像这样:

s = pl.Series([1.2345, 2.3456, 3.4567])

s.cast(pl.String, fmt="%0.2f") # fmt obviously isn't an argument

我目前的方法如下:

n = 2 # number of decimals desired
expr = pl.concat_str((
    s.floor().cast(pl.Int32).cast(pl.String),
    pl.lit('.'),
    ((s%1)*(10**n)).round(0).cast(pl.Int32).cast(pl.String)
)).str.pad_end(width)

即将小数点前和小数点后分开,单独格式化为字符串,然后连接在一起。有更简单的方法吗?

预期输出:

shape: (3,)
Series: '' [str]
[
    "1.23"
    "2.34"
    "3.45"
]
python python-polars
1个回答
3
投票

我不知道在转换时指定格式的直接方法,但这里有两种简单的方法来获取特定的小数位数。

使用
write_csv

我们可以使用

write_csv
来设置
float_precision
参数。 我们可以使用
read_csv
再次重新解析以获得结果。 (这比你想象的要快得多。)

注意:我们必须在

infer_schema_length=0
中使用
read_csv
来防止将字符串解析回浮点数。

s = pl.Series([1.2345, 2.3456, 3.4567])

n = 2
(
    pl.read_csv(
        pl.select(s)
          .write_csv(float_precision=n)
          .encode(), # bytes can be given to read_csv, or use io.StringIO
        infer_schema_length=0
    )
    .to_series()
)
shape: (3,)
Series: '1.23' [str]
[
        "1.23"
        "2.35"
        "3.46"
]

用零填充,然后使用单个正则表达式

另一种方法是转换为字符串,然后附加零。 由此,我们可以使用单个正则表达式来提取结果。

n = 2
zfill = '0' * n
regex = r"^([^\.]*\..{" + str(n) + r"})"
(
    pl.select(s)
    .with_columns(
        pl.concat_str(
            pl.col(pl.Float64).cast(pl.String),
            pl.lit(zfill)
        )
        .str.extract(regex)
    )
    .to_series()
)

shape: (3,)
Series: '' [str]
[
        "1.23"
        "2.34"
        "3.45"
]
© www.soinside.com 2019 - 2024. All rights reserved.