如何在Polars数据框中将空列表替换为null/None以统计缺失值?
如何将Polars DataFrame中的空列表替换为null/None
给定包含空列表的Polars DataFrame,需要把空列表替换为null/None,以便将其统计为缺失值。
输入示例
import polars as pl df = pl.DataFrame([ pl.Series('contacts', [[], [], ['1081'], ['1313'], ['3657']], dtype=pl.List(pl.String)), pl.Series('line_items', [[], [], [], [], []], dtype=pl.List(pl.String)), ])
问题分析
你之前尝试的写法无法识别空列表,因为pl.col(pl.List(pl.Null))是筛选元素类型为Null的列表列,而不是判断列表是否为空:
df.with_columns( pl.when(pl.col(pl.List(pl.Null))) .then(None) .otherwise(pl.col(pl.List)) .name.keep() )
正确解法
要检测空列表,需通过list.lengths()获取列表长度,判断是否等于0,再替换为None。
批量处理所有列表列
如果需要处理DataFrame中所有列表类型的列,可以用pl.col(pl.List)匹配:
df = df.with_columns( pl.col(pl.List) .when(pl.col().list.lengths() == 0) .then(None) .name.keep() )
指定列处理
如果只需要处理特定列,直接指定列名即可:
df = df.with_columns( pl.col("contacts", "line_items") .when(pl.col().list.lengths() == 0) .then(None) .name.keep() )
执行结果
运行后得到符合预期的DataFrame:
shape: (5, 2) ┌───────────┬────────────┐ │ contacts ┆ line_items │ │ --- ┆ --- │ │ list[str] ┆ list[str] │ ╞═══════════╪════════════╡ │ null ┆ null │ │ null ┆ null │ │ ["1081"] ┆ null │ │ ["1313"] ┆ null │ │ ["3657"] ┆ null │ └───────────┴────────────┘
内容的提问来源于stack exchange,提问作者Valentine
相关产品推荐
相关产品推荐

