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

在Polars中如何将含"true"/"false"的字符串列转为布尔类型?

将含"true"/"false"字符串的列转为Boolean类型的最佳方法

replace_strict

该方案可行

df = pl.DataFrame({"str_col": ["false", "true"]})

df.with_columns(
    pl.col("str_col").replace_strict({"false":False, "true":True})
)

执行结果:

shape: (2, 1)
┌─────────┐
│ str_col │
│ ---     │
│ bool    │
╞═════════╡
│ false   │
│ true    │
└─────────┘

直接转换(direct cast)

尝试直接转换的代码:

df["str_col"].cast(pl.Boolean).unique()

执行后报错:

InvalidOperationError: casting from Utf8View to Boolean not supported

间接转换(indirect cast)

思路是先转为Categorical数据类型,实际执行结果如下:

print(df["str_col"].unique())
print(df["str_col"].cast(pl.Categorical).unique())
print(df["str_col"].cast(pl.Categorical).cast(pl.Boolean).unique())

执行结果:

shape: (2,)
Series: 'str_col' [str]
[
    "true"
    "false"
]
shape: (2,)
Series: 'str_col' [cat]
[
    "false"
    "true"
]
shape: (2,)
Series: 'str_col' [bool]
[
    false
    true
]

内容的提问来源于stack exchange,提问作者Martin Zäch

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 04:39:34