如何在Python Polars中统计分组汇总的列空值(null)?
如何按分组统计列中的空值?
我用Python Polars创建了如下DataFrame:
import polars as pl df = pl.DataFrame({ 'prod': ['apple','apple','banana','lemon','lemon','lemon'], 'price': [11, None, 14, 21, None, 23] })
输出结果:
shape: (6, 2) ┌────────┬───────┐ │ prod ┆ price │ │ --- ┆ --- │ │ str ┆ i64 │ ╞════════╪═══════╡ │ apple ┆ 11 │ │ apple ┆ null │ │ banana ┆ 14 │ │ lemon ┆ 21 │ │ lemon ┆ null │ │ lemon ┆ 23 │ └────────┴───────┘
我尝试了以下代码,但没得到预期结果:
df.group_by('prod').agg(pl.count().alias('COUNT'), pl.when(pl.col('price').is_null()).then(1).count().alias('NULLS') ).sort(by='prod')
执行结果:
shape: (3, 3) ┌────────┬───────┬───────┐ │ prod ┆ COUNT ┆ NULLS │ │ --- ┆ --- │ │ str ┆ u32 ┆ u32 │ ╞════════╪═══════╪═══════╡ │ apple ┆ 2 ┆ 1 │ │ banana ┆ 1 ┆ 0 │ │ lemon ┆ 3 ┆ 1 │ └────────┴───────┴───────┘
你的执行结果其实是正确的,但代码写法可以更简洁直观。以下是两种更符合Polars惯用逻辑的实现方式:
方法一:直接用is_null().sum()
is_null()会返回布尔值序列(空值对应True,非空对应False),对其求和即可得到空值的数量:
df.group_by('prod').agg( pl.count().alias('COUNT'), pl.col('price').is_null().sum().alias('NULLS') ).sort(by='prod')
方法二:修正原有逻辑
你原代码中使用count()会统计所有行数,应该替换为sum()来统计符合条件的记录数:
df.group_by('prod').agg( pl.count().alias('COUNT'), pl.when(pl.col('price').is_null()).then(1).sum().alias('NULLS') ).sort(by='prod')
两种方法都会得到和你当前一致的正确结果。
内容的提问来源于stack exchange,提问作者lmocsi
相关产品推荐
相关产品推荐

