根据熊猫数据框中的多个条件删除行

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

我想在满足几个条件时删除行:

示例数据框如下所示:

        one       two     three      four
0 -0.225730 -1.376075  0.187749  0.763307
1  0.031392  0.752496 -1.504769 -1.247581
2 -0.442992 -0.323782 -0.710859 -0.502574
3 -0.948055 -0.224910 -1.337001  3.328741
4  1.879985 -0.968238  1.229118 -1.044477
5  0.440025 -0.809856 -0.336522  0.787792
6  1.499040  0.195022  0.387194  0.952725
7 -0.923592 -1.394025 -0.623201 -0.738013
8 -1.775043 -1.279997  0.194206 -1.176260
9 -0.602815  1.183396 -2.712422 -0.377118

我想根据以下条件删除行:

col 'one', 'two', or 'three' 的值大于 0 的行; and col 'four' 小于 0 的值应删除。

然后我尝试实现如下:

df = df[df.one > 0 or df.two > 0 or df.three > 0 and df.four < 1]

但是,它会导致错误消息如下:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

有人可以帮助我如何根据多个条件删除吗?

python pandas dataframe indexing boolean-logic
2个回答
52
投票

由于我不是 100% 清楚的原因

pandas
与按位逻辑运算符
|
&
一起玩得很好,但不是布尔运算符
or
and
.

试试这个:

df = df[(df.one > 0) | (df.two > 0) | (df.three > 0) & (df.four < 1)]

0
投票

drop
可用于删除行

最明显的方法是在给定条件的情况下构造一个布尔掩码,通过它过滤索引以获得要删除的索引数组,并使用

drop()
删除这些索引。如果条件是:

col 'one', 'two', or 'three' 的值大于 0 的行; and col 'four' 小于 0 的值应该被删除。

然后下面的作品。

msk = (df['one'].gt(0) | df['two'].gt(0) | df['three'].gt(0)) & df['four'].lt(0)
idx_to_drop = df.index[msk]
df1 = df.drop(idx_to_drop)

条件的第一部分,即

col 'one', 'two', or 'three' greater than 0
可以用
.any(axis=1)
写得更简洁一点:

msk = df[['one', 'two', 'three']].gt(0).any(axis=1) & df['four'].lt(0)

保持行的补码下降

Deleting/removing/dropping rows 与keeping rows相反。因此,执行此任务的另一种方法是否定 (

~
) 用于删除行的布尔掩码并通过它过滤数据框。

msk = df[['one', 'two', 'three']].gt(0).any(axis=1) & df['four'].lt(0)
df1 = df[~msk]

query()
要保留的行

pd.DataFrame.query()
是一个非常易读的 API,用于过滤要保留的行。它还“理解”
and
/
or
等。所以下面的作品。

# negate the condition to drop
df1 = df.query("not ((one > 0 or two > 0 or three > 0) and four < 0)")

# the same condition transformed using de Morgan's laws
df1 = df.query("one <= 0 and two <= 0 and three <= 0 or four >= 0")

以上所有执行以下转换:

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