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

Polars替换空字符串异常,求官方推荐的规范处理方法

Polars中空字符串替换的正确方法

问题场景

使用pl.read_excel()读取Excel文件得到DataFrame后,空单元格被识别为""(空字符串)而非标准的Null。尝试用str.replace("", "n.a.", literal=True)替换空字符串时,所有非空值前都被插入了替换内容,不符合预期。

最小可复现示例(MVE)

import polars as pl

df = pl.DataFrame({"test": ["A", "B", "", "C"]})
df = df.with_columns(pl.col("test").str.replace("", "n.a.", literal=True))
df.head()

实际返回结果

shape: (4, 1)
test
str
"n.a.A"
"n.a.B"
"n.a."
"n.a.C"

期望结果

shape: (4, 1)
test
str
"A"
"B"
"n.a."
"C"

官方推荐的惯用方法

方法1:条件判断精准匹配(最直观)

通过when/then/otherwise直接判断列值是否为空字符串,仅替换完全匹配的条目:

import polars as pl

df = pl.DataFrame({"test": ["A", "B", "", "C"]})
df = df.with_columns(
    pl.when(pl.col("test") == "")
    .then("n.a.")
    .otherwise(pl.col("test"))
    .alias("test")
)
print(df.head())

方法2:正则匹配整行空字符串

利用正则表达式^$匹配完全为空的字符串,结合str.replace_all实现精准替换:

df = pl.DataFrame({"test": ["A", "B", "", "C"]})
df = df.with_columns(
    pl.col("test").str.replace_all(r"^$", "n.a.")
)
print(df.head())

方法3:转Null后填充(适合标准化缺失值)

先将空字符串转为Polars标准的Null,再用fill_null统一填充,适合后续需要处理缺失值的场景:

df = pl.DataFrame({"test": ["A", "B", "", "C"]})
df = df.with_columns(
    pl.col("test").when(pl.col("test") == "").then(None).otherwise(pl.col("test")).fill_null("n.a.")
)
print(df.head())

原方法失效原因

str.replace("", "n.a.", literal=True)会匹配字符串中的任意空位置(包括每个非空字符串的起始位置),因此会在所有非空值前插入替换内容,无法实现仅替换空字符串的需求。

内容的提问来源于stack exchange,提问作者Vega

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 12:10:13