使用 Polars 返回其中一列中至少有一个 null 的所有行

问题描述 投票:0回答:2

我需要预定义列之一中具有 null 的所有行。 我基本上需要this,但我还有一个我似乎无法弄清楚的要求。 并非每一列都需要检查。

我有一个函数,它返回列表中需要检查的列的名称。

假设这是我的数据框:

data = pl.from_repr("""
┌───────┬───────┬─────┬───────┐
│ a     ┆ b     ┆ c   ┆ d     │
│ ---   ┆ ---   ┆ --- ┆ ---   │
│ str   ┆ str   ┆ str ┆ bool  │
╞═══════╪═══════╪═════╪═══════╡
│ abc   ┆ null  ┆ u   ┆ true  │
│ def   ┆ abc   ┆ v   ┆ true  │
│ ghi   ┆ def   ┆ null┆ true  │
│ jkl   ┆ uvw   ┆ x   ┆ true  │
│ mno   ┆ xyz   ┆ y   ┆ null  │
│ qrs   ┆ null  ┆ z   ┆ null  │
└───────┴───────┴─────┴───────┘
""")

data.filter(polars.any_horizontal(polars.all().is_null()))
给我任何列包含
null
的所有行。

有时,列

c
包含
null
就可以了,所以我们不要检查它。

我想要的是这个:

┌───────┬───────┬─────┬───────┐
│ a     ┆ b     ┆ c   ┆ d     │
│ ---   ┆ ---   ┆ --- ┆ ---   │
│ str   ┆ str   ┆ str ┆ bool  │
╞═══════╪═══════╪═════╪═══════╡
│ abc   ┆ null  ┆ u   ┆ true  │
│ mno   ┆ xyz   ┆ y   ┆ null  │
│ qrs   ┆ null  ┆ z   ┆ null  │
└───────┴───────┴─────┴───────┘

即使 c 列中有空值,也不会显示第 3 行。

columns = ["a", "b", "d"]
data.filter(polars.any_horizontal(polars.all(*columns).is_null()))

这给了我

polars.exceptions.SchemaError: invalid series dtype: expected 'Boolean', got 'str'

我想也许列没有对齐或其他什么原因,因为数据的列比过滤器使用的列多,所以我这样做了。

columns = ["a", "b", "d"]
# notice `.select(columns)` here
data.select(columns).filter(polars.any_horizontal(polars.all(*columns).is_null()))

但是仍然遇到同样的错误。 如何获取在

null
列之一中包含
["a", "b", "d"]
的完整数据行

python null python-polars
2个回答
0
投票
data.filter(pl.any_horizontal(pl.exclude("c").is_null()))

0
投票

我需要的是

polars.col(names)
而不是
polars.all(names)
。 根据文档
polars.all(names)
!=
polars.col(names)

此函数是

col(names).all()

的语法糖

这有效:

columns = ["a", "b", "d"]
data.filter(polars.any_horizontal(polars.col(*columns).is_null()))
© www.soinside.com 2019 - 2024. All rights reserved.