如何将Polars DataFrame中的空列表转换为null?
解决Polars DataFrame中空列表转null的问题
你的需求是把列表类型列里的空列表统一转为null,但现有代码没生效,问题出在then(None)的类型推断上,Polars需要明确的类型匹配才能正确转换。以下是修正后的解决方案:
问题分析
你原代码中使用then(None)时,Polars无法准确推断出返回值的类型(列表类型的null),导致转换逻辑没有实际生效。另外可以用更直观的list.is_empty()方法判断空列表,替代list.len() == 0。
解决方案
1. 批量处理所有列表类型列
这种方式会自动识别DataFrame中所有列表类型的列,将其中的空列表转为null:
# 遍历所有列表类型列 for col in df.select(pl.col(pl.List)).columns: df = df.with_columns( pl.col(col).when(pl.col(col).list.is_empty()).then(pl.null()).otherwise(pl.col(col)) )
2. 针对指定列处理
如果只需要处理特定的列表列(比如你的spcLink列),可以直接指定列名:
df = df.with_columns( pl.col("spcLink").when(pl.col("spcLink").list.is_empty()).then(pl.null()).otherwise(pl.col("spcLink")) )
3. 更简洁的批量写法
使用Polars的列选择语法,一行代码完成所有列表列的转换:
df = df.with_columns( pl.col(pl.List).when(pl.col(pl.List).list.is_empty()).then(pl.null()) )
这里可以省略otherwise(pl.col(...)),因为when语句中没有匹配的行会保留原列值。
验证结果
执行上述代码后,再查看你的DataFrame:
print(df[["spcLink", "proprietors"]])
此时spcLink列中的空列表会被转换为null,和proprietors列的格式统一。
内容的提问来源于stack exchange,提问作者tsorn
相关产品推荐
相关产品推荐

