一个示例数据帧如下:
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的价值为“一个”,“两个”,
or
'三'大于0; col的col'四'的值应删除小于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()
有人可以帮助我如何根据多种条件删除?
由于我的原因对我而言并不清楚,
pandas
与位逻辑运算符和
|
the the the Boolean note note note nots
&
and
可以用来掉下行
最明显的方法是在情况下构建布尔掩码,通过其过滤索引,以获取一系列索引,以使用
df = df[(df.one > 0) | (df.two > 0) | (df.three > 0) & (df.four < 1)]
来掉落和删除这些索引。如果条件是:col的价值为“一个”,“两个”,
or
'三'大于0; col的col'四'的值应删除小于0。the以下工作。
drop
drop()
:来简单地写一点。
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)
将行的补充保留为降低 dreating/demoving/drops行是保持行的倒数。因此,执行此任务的另一种方法是否定(
行col 'one', 'two', or 'three' greater than 0
)布尔蒙版,以删除行并用它过滤dataframe。
行保持.any(axis=1)
msk = df[['one', 'two', 'three']].gt(0).any(axis=1) & df['four'].lt(0)
~
是一个非常可读的API,用于过滤行保持。它也“理解”
msk = df[['one', 'two', 'three']].gt(0).any(axis=1) & df['four'].lt(0)
df1 = df[~msk]
/
query()
等。因此,以下工作正常。
pd.DataFrame.query()
上述所有人都执行以下转换: