极坐标截去小数

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

我正在尝试将 DataFrame 中的浮点数截断为所需的小数位数。我发现这可以使用 Pandas 和 NumPy here 来完成,但我也发现使用

polars.Config.set_float_precision
也可以实现。

以下是我目前的方法,但我认为我可能会采取额外的步骤。

import polars as pl

data = {
    "name": ["Alice", "Bob", "Charlie"],
    "grade": [90.23456, 80.98765, 85.12345],
}

df = pl.DataFrame(data)
df.with_columns(
# Convert to string
    pl.col("grade").map_elements(lambda x: f"{x:.5f}", return_dtype=pl.String).alias("formatted_grade")
).with_columns(
# Slice to get my desired decimals
    pl.col("formatted_grade").str.slice(0, length = 4)
).with_columns(
# Convert it again to Float
    pl.col("formatted_grade").cast(pl.Float64)
)
python dataframe precision python-polars
1个回答
0
投票

您可以像这样使用 Polars - Numpy 集成

df = df.with_columns(truncated_grade=np.trunc(pl.col("grade") * 10) / 10)

输出:

┌─────────┬──────────┬─────────────────┐
│ name    ┆ grade    ┆ truncated_grade │
│ ---     ┆ ---      ┆ ---             │
│ str     ┆ f64      ┆ f64             │
╞═════════╪══════════╪═════════════════╡
│ Alice   ┆ 90.23456 ┆ 90.2            │
│ Bob     ┆ 80.98765 ┆ 80.9            │
│ Charlie ┆ 85.12345 ┆ 85.1            │
└─────────┴──────────┴─────────────────┘

完整代码:

import numpy as np
import polars as pl

data = {
    "name": ["Alice", "Bob", "Charlie"],
    "grade": [90.23456, 80.98765, 85.12345],
}

df = pl.DataFrame(data)
df = df.with_columns(truncated_grade=np.trunc(pl.col("grade") * 10) / 10)

print(df)
© www.soinside.com 2019 - 2024. All rights reserved.