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

如何在Polars中将字符串列转为整数并将非数值转为Null

Polars 0.19.0 将字符串列转为整数并替换非数值为null的正确实现

解决方案1:使用cast方法(推荐)

Polars的cast方法原生支持字符串到数值类型的转换,设置strict=False后,所有无法解析为整数的非数值字符串会自动转为null,完全匹配你的需求:

import polars as pl

df = pl.DataFrame({
    "str_column": ["3", "4", "unavailable", "random_String", "17"]
})

# 执行转换并覆盖原列(如需保留原列可重命名新列,比如.alias("int_column"))
df = df.with_columns(pl.col("str_column").cast(pl.Int64, strict=False))
print(df)

执行后输出:

┌────────────┐
│ str_column │
│ ---        │
│ i64        │
╞════════════╡
│ 3          │
│ 4          │
│ null       │
│ null       │
│ 17         │
└────────────┘

解决方案2:修复str.parse_int的使用方式

你使用str.parse_int(strict=False)时出现全null的问题,主要是两个原因:

  1. 未赋值回DataFrame:Polars是不可变数据结构,with_columns会返回新的DataFrame,必须重新赋值给变量才能看到转换结果。
  2. 旧版本参数缺失:在Polars 0.19.0中,str.parse_int需要明确指定base=10(十进制),否则可能解析逻辑异常导致纯数字字符串也失败:
df = df.with_columns(pl.col("str_column").str.parse_int(base=10, strict=False))

执行这段代码也能得到你期望的结果。

关键说明

cast方法在处理字符串转数值的场景下更直观,兼容性更好;而str.parse_int更适合需要自定义进制解析的场景。根据你的需求,cast是更优选择。

内容的提问来源于stack exchange,提问作者Camilo Piñón

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 18:43:12