使用 NOT 和 AND 条件过滤数据帧

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

我知道这个问题已被问过多次,但由于某种原因,它不适用于我的情况。

所以我想使用 NOT 和 AND 条件来过滤数据帧。 例如,我的数据框 df 看起来像:

col1    col2
a       1
a       2
b       3
b       4
b       5
c       6

现在,我想用一个条件来删除where

col1 has "a" AND col2 has 2
我生成的数据框应如下所示:

col1    col2
a       1
b       3
b       4
b       5
c       6

我尝试了这个:尽管我使用了

&
但它删除了 col1 中具有“a”的所有行。

df = df[(df['col1'] != "a") & (df['col2'] != "2")]
python-3.x pandas
2个回答
2
投票

删除

col1 is "a" AND col2 is 2
处的单元格意味着保留
col1 isn't "a" OR col2 isn't 2
处的单元格(
A AND B
的否定是
NOT(A) OR NOT(B)
):

df = df[(df['col1'] != "a") | (df['col2'] != 2)]   #   or "2", depending on whether the `2` is an int or a str

0
投票
df1.query("not (col1=='a' and col2==2)")
© www.soinside.com 2019 - 2024. All rights reserved.