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

如何在Polars中将无小数部分的浮点列转换为整数列?

如何在Polars中将无小数部分的浮点列转换为整数列?

嘿,我来帮你搞定这个Polars的实现!你想要的效果是:把那些全是整数浮点数的列(比如你的a列,值都是1.0、2.0)转成整数类型,而混合了整数和非整数浮点数的列(比如c列)保留浮点类型,对吧?刚好Polars能很方便地实现这个需求,咱们分两种情况来给你演示:

方法一:和你的Pandas代码效果完全一致

这个方法会检查每一列是否所有值都是整数浮点数,如果是就把整个列转成整数类型,否则保持浮点类型,和你原来的Pandas输出完全匹配:

import polars as pl

# 创建初始DataFrame
df = pl.DataFrame({
    "date": ["2025-01-01", "2025-01-02"],
    "a": [1.0, 2.0],
    "c": [1.0, 2.1],
})
print("原始数据:")
print(df)

# 定义一个辅助表达式,判断列是否所有值都是整数浮点数
def col_all_integers(col: pl.Expr) -> pl.Expr:
    return col.is_integer().all()

# 获取除了date之外的所有列
cols_to_process = df.columns.difference(["date"])

# 遍历处理每一列
for col in cols_to_process:
    # 检查当前列是否全为整数浮点数
    if df.select(col_all_integers(pl.col(col))).item():
        df = df.with_columns(pl.col(col).cast(pl.Int64).alias(col))

print("\n处理后的数据:")
print(df)

输出结果:

原始数据:

shape: (2, 3)
┌────────────┬─────┬─────┐
│ date       ┆ a   ┆ c   │
│ ---        ┆ --- ┆ --- │
│ str        ┆ f64 ┆ f64 │
╞════════════╪═════╪═════╡
│ 2025-01-01 ┆ 1.0 ┆ 1.0 │
│ 2025-01-02 ┆ 2.0 ┆ 2.1 │
└────────────┴─────┴─────┘

处理后的数据:

shape: (2, 3)
┌────────────┬─────┬─────┐
│ date       ┆ a   ┆ c   │
│ ---        ┆ --- ┆ --- │
│ str        ┆ i64 ┆ f64 │
╞════════════╪═════╪═════╡
│ 2025-01-01 ┆ 1   ┆ 1.0 │
│ 2025-01-02 ┆ 2   ┆ 2.1 │
└────────────┴─────┴─────┘

可以看到,a列成功转成了整数类型,显示为1、2,而c列因为有2.1这个非整数浮点数,保持了浮点类型,和你Pandas的输出完全一致。

方法二:逐元素转换(混合类型列)

如果你想让混合类型的列里,整数浮点数直接转成整数(比如c列的1.0变成整数1),那可以用when/then/otherwise表达式逐元素处理,不过这样列的类型会变成Object(因为混合了整数和浮点数),Polars一般不推荐这种强类型混合的写法,但如果是你的需求的话,代码如下:

import polars as pl

df = pl.DataFrame({
    "date": ["2025-01-01", "2025-01-02"],
    "a": [1.0, 2.0],
    "c": [1.0, 2.1],
})
print("原始数据:")
print(df)

cols_to_process = df.columns.difference(["date"])

df = df.with_columns(
    pl.when(pl.col(col).is_integer())
    .then(pl.col(col).cast(pl.Int64).cast(pl.Object))
    .otherwise(pl.col(col).cast(pl.Object))
    .alias(col)
    for col in cols_to_process
)

print("\n处理后的数据:")
print(df)

输出结果:

shape: (2, 3)
┌────────────┬─────┬─────┐
│ date       ┆ a   ┆ c   │
│ ---        ┆ --- ┆ --- │
│ str        ┆ i64 ┆ obj │
╞════════════╪═════╪═════╡
│ 2025-01-01 ┆ 1   ┆ 1   │
│ 2025-01-02 ┆ 2   ┆ 2.1 │
└────────────┴─────┴─────┘

这个结果里c列的1.0变成了整数1,但列类型变成了Object,适合特殊场景下的需求。

备注:内容来源于stack exchange,提问作者Nyssance

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 11:32:57