如何在Polars DataFrame中仅对指定列移除空值?
问题:移除Polars DataFrame中指定列全为空的行
想要移除Polars DataFrame中指定列(所有以eat开头的列)全为空的行,使用with_columns操作时出现错误,求正确实现方式。
原始数据
数据构造代码
import polars as pl df = pl.DataFrame( { "id": ["NY", "TK", "FD"], "eat2000": [1, None, 3], "eat2001": [-2, None, 4], "eat2002": [None, None, None], "eat2003": [-9, None, 8], "eat2004": [None, None, 8] } ); df
数据输出
┌─────┬─────────┬─────────┬─────────┬─────────┬─────────┐ │ id ┆ eat2000 ┆ eat2001 ┆ eat2002 ┆ eat2003 ┆ eat2004 │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 ┆ f64 ┆ i64 ┆ i64 │ ╞═════╪═════════╪═════════╪═════════╪═════════╪═════════╡ │ NY ┆ 1 ┆ -2 ┆ null ┆ -9 ┆ null │ │ TK ┆ null ┆ null ┆ null ┆ null ┆ null │ │ FD ┆ 3 ┆ 4 ┆ null ┆ 8 ┆ 8 │ └─────┴─────────┴─────────┴─────────┴─────────┴─────────┘
错误尝试及报错
尝试代码
col_list = [word for word in df.columns if word.startswith(("eat"))] ( df .with_columns( pl.col(col_list).filter(~pl.fold(True, lambda acc, s: acc & s.is_null(), pl.all())) ) )
报错信息
InvalidOperationError: dtype String not supported in 'not' operation
正确实现方式
错误原因
- 需求是过滤行,但误用了用于修改列的
with_columns方法,应该使用filter方法。 pl.all()会包含DataFrame中所有列(包括字符串类型的id列),导致执行not操作时因字符串类型不支持而报错。
解决方案代码
方法一:判断指定列至少有一个非空值
col_list = [word for word in df.columns if word.startswith(("eat"))] result = df.filter(pl.col(col_list).is_not_null().any(axis=1)) print(result)
方法二:判断指定列并非全为空
col_list = [word for word in df.columns if word.startswith(("eat"))] result = df.filter(~pl.col(col_list).is_null().all(axis=1)) print(result)
最终输出结果
┌─────┬─────────┬─────────┬─────────┬─────────┬─────────┐ │ id ┆ eat2000 ┆ eat2001 ┆ eat2002 ┆ eat2003 ┆ eat2004 │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 ┆ f64 ┆ i64 ┆ i64 │ ╞═════╪═════════╪═════════╪═════════╪═════════╪═════════╡ │ NY ┆ 1 ┆ -2 ┆ null ┆ -9 ┆ null │ │ FD ┆ 3 ┆ 4 ┆ null ┆ 8 ┆ 8 │ └─────┴─────────┴─────────┴─────────┴─────────┴─────────┘
内容的提问来源于stack exchange,提问作者codedancer
相关产品推荐
相关产品推荐

