Polars条件分支代码报错求助:TypeError: col输入参数无效
问题修复:Polars条件分支赋值错误
错误原因
你遇到的TypeError是因为误用了pl.col()函数:pl.col()的作用是引用DataFrame中的现有列,参数需要是列名字符串或数据类型,而你直接传入整数1/0,不符合它的参数要求。要生成常量值的列,应该用pl.lit()(字面量函数,用于创建常量表达式)。
修复后的代码
基础修复版本
import polars as pl import numpy as np np.random.seed(12) df = pl.DataFrame( { "nrs": [1, 2, 3, None, 5], "names": ["foo", "ham", "spam", "egg", None], "random": np.random.rand(5), "groups": ["A", "A", "B", "C", "B"], } ) # 修复:用pl.lit()替代pl.col()来生成常量值 result_df = df.with_columns( pl.when(pl.col('nrs') == 1).then(pl.lit(1)) .when(pl.col('names') == 'ham').then(pl.lit(1)) .when(pl.col('random') == 0.014575).then(pl.lit(1)) .otherwise(pl.lit(0)) .alias('my_new_column_flag') ) print(result_df)
更简洁的写法(合并多条件)
因为你的需求是任一条件满足则赋值1,可以用逻辑或|合并所有条件,代码更简洁高效:
result_df = df.with_columns( pl.when( (pl.col('nrs') == 1) | (pl.col('names') == 'ham') | (pl.col('random') == 0.014575) ).then(pl.lit(1)).otherwise(pl.lit(0)) .alias('my_new_column_flag') )
补充说明(针对R语言背景)
如果你熟悉R的dplyr::case_when(),Polars的pl.when().then().otherwise()逻辑类似,但有两点差异需要注意:
- R中直接写常量值即可,而Polars需要用
pl.lit()包装常量,因为Polars是表达式式API,所有操作都需要用表达式对象 - 多条件合并时,Polars用
|表示逻辑或,和R中的|逻辑一致,但要注意用括号包裹每个独立条件
内容的提问来源于stack exchange,提问作者John Smith
相关产品推荐
相关产品推荐

