仅保留具有子集的重复行

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

我有一个数据框,我想探索并仅查看基于两列或更多列的重复行。

例如:

df = pl.DataFrame({"A": [1, 6, 5, 4, 5, 6],
                   "B": ["A", "B", "C", "D", "C", "A"],
                   "C": [2, 2, 2, 1, 1, 1]})

我只想返回 A 列和 B 列的重复组合。我试过了:

df.filter(pl.col("A", "B").is_duplicated()) # Returns: This is ambiguous. Try to combine the predicates with the 'all' or `any' expression.

中间添加.all()时,结果与上面相同

df.filter(pl.col("A", "B").all().is_duplicated()) # Same as above

保持“none”的唯一性返回与我想要的相反的结果,所以尝试了以下方法:

df.unique(subset=["A", "B"], keep="none").is_not() # 'DataFrame' object has no attribute 'is_not'

预期输出将仅看到行:

shape: (2, 3)
┌─────┬─────┬─────┐
│ A   | B   | C   │
│ --- | --- | --- │
│ i64 | str | i64 │
╞═════╪═════╪═════╡
│ 5   | C   | 2   │
│ 5   | C   | 1   │
└─────┴─────┴─────┘
python-polars
2个回答
2
投票

使用

.struct
是将多个表达式组合在一起作为“单个实体”。

然后您可以使用

.is_duplicated

df.filter(pl.struct(["A", "B"]).is_duplicated())
shape: (2, 3)
┌─────┬─────┬─────┐
│ A   | B   | C   │
│ --- | --- | --- │
│ i64 | str | i64 │
╞═════╪═════╪═════╡
│ 5   | C   | 2   │
│ 5   | C   | 1   │
└─────┴─────┴─────┘

将多个项目传递给

.col()

pl.col(["A", "B"]).is_duplicated()

相当于

pl.col("A").is_duplicated(), pl.col("B").is_duplicated()

这就是需要结构步骤的原因:

>>> df.select(pl.struct(["A", "B"]))
shape: (6, 1)
┌───────────┐
│ A         │
│ ---       │
│ struct[2] │
╞═══════════╡
│ {1,"A"}   │
│ {6,"B"}   │
│ {5,"C"}   │
│ {4,"D"}   │
│ {5,"C"}   │
│ {6,"A"}   │
└───────────┘

1
投票

在文档中我们有以下示例:

示例

df = pl.DataFrame(
    {
        "a": [1, 2, 3, 1],
        "b": ["x", "y", "z", "x"],
    }
)
df.is_duplicated()
shape: (4,)
Series: '' [bool]
[
        true
        false
        false
        true
]

此蒙版可用于可视化重复的线条,如下所示:

df.filter(df.is_duplicated())
shape: (2, 2)
┌─────┬─────┐
│ a   ┆ b   │
│ --- ┆ --- │
│ i64 ┆ str │
╞═════╪═════╡
│ 1   ┆ x   │
│ 1   ┆ x   │
└─────┴─────┘

https://pola-rs.github.io/polars/py-polars/html/reference/dataframe/api/polars.DataFrame.is_duplicated.html#polars.DataFrame.is_duplicated

© www.soinside.com 2019 - 2024. All rights reserved.