在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
相关产品推荐
相关产品推荐

