根据特定列包含对列表中的对的行来过滤极坐标 DataFrame

pik*_*aft 4 python python-3.x python-polars

在此示例中,在 columns 上["foo", "ham"],我希望删除第 1 行和第 4 行,因为它们与列表中的一对匹配

df = pl.DataFrame(
    {
        "foo": [1, 1, 2, 2, 3, 3, 4],
        "bar": [6, 7, 8, 9, 10, 11, 12],
        "ham": ["a", "b", "c", "d", "e", "f", "b"]
    }
)
pairs = [(1,"b"),(3,"e"),(4,"g")]
Run Code Online (Sandbox Code Playgroud)

以下内容对我有用,但我认为当数据框和对列表很大时这会出现问题。

for a, b in pairs:
    df = df.filter(~(pl.col('foo') == a) | ~(pl.col('ham') == b))
Run Code Online (Sandbox Code Playgroud)

我认为这是这个问题的 Pandas 实现Pandas: How to remove rows from a dataframe based on a tuples list made value in TWO columns?

我不确定 Polars 的实现是什么。

(我认为这个问题可以推广到任意数量的选定列和组中任意数量的元素。例如,它可以是另一个数据框,而不是成对的列表。您可以得到“集合差异”,即行,基于特定列的两个数据帧。)

jqu*_*ous 8

看起来像反连接

\n
schema = ["foo", "ham"]\n\ndf.with_row_count().join(\n   pl.DataFrame(pairs, schema=schema), \n   on=schema, \n   how="anti"\n)\n
Run Code Online (Sandbox Code Playgroud)\n
shape: (5, 4)\n\xe2\x94\x8c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xac\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xac\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xac\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x90\n\xe2\x94\x82 row_nr \xe2\x94\x86 foo \xe2\x94\x86 bar \xe2\x94\x86 ham \xe2\x94\x82\n\xe2\x94\x82 ---    \xe2\x94\x86 --- \xe2\x94\x86 --- \xe2\x94\x86 --- \xe2\x94\x82\n\xe2\x94\x82 u32    \xe2\x94\x86 i64 \xe2\x94\x86 i64 \xe2\x94\x86 str \xe2\x94\x82\n\xe2\x95\x9e\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\xaa\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\xaa\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\xaa\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\xa1\n\xe2\x94\x82 0      \xe2\x94\x86 1   \xe2\x94\x86 6   \xe2\x94\x86 a   \xe2\x94\x82\n\xe2\x94\x82 2      \xe2\x94\x86 2   \xe2\x94\x86 8   \xe2\x94\x86 c   \xe2\x94\x82\n\xe2\x94\x82 3      \xe2\x94\x86 2   \xe2\x94\x86 9   \xe2\x94\x86 d   \xe2\x94\x82\n\xe2\x94\x82 5      \xe2\x94\x86 3   \xe2\x94\x86 11  \xe2\x94\x86 f   \xe2\x94\x82\n\xe2\x94\x82 6      \xe2\x94\x86 4   \xe2\x94\x86 12  \xe2\x94\x86 b   \xe2\x94\x82\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xb4\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xb4\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xb4\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x98\n
Run Code Online (Sandbox Code Playgroud)\n