首页 > 解决方案 > 按多个条件过滤 numpy 数组行时的问题

问题描述

我想通过多个条件过滤一个 numpy 数组。我找到 了这个线程并在我的数据集上测试了切片方法,但我得到了意想不到的结果。好吧,至少对我来说,它们是出乎意料的,因为我可能只是在理解按位运算符或其他东西的功能时遇到了问题:/

只是为了让您了解数据:

test.shape
>>(222988, 2)

stats.describe(all_output[:, 0])
>>DescribeResult(nobs=222988, minmax=(2.594e-05, 74.821), mean=11.106, variance=108.246, [...])

stats.describe(all_output[:, 1])
>>DescribeResult(nobs=222988, minmax=(0.001, 8.999), mean=3.484, variance=7.606, [...])

现在,做一些基本的过滤:

test1 = test[(test[:, 0] >= 30) & (test[:, 1] <= 2)] 

test1.shape
>>(337, 2)

这些实际上是我不想在我的数据集中拥有的行所以如果我做我认为相反的事情......

test2 = test[(test[:, 0] <= 30) & (test[:, 1] >= 2)] 

test2.shape
>>(112349, 2)

我希望结果是 (222651, 2)。我想我做错了一些令人尴尬的简单事情?这里的任何人都可以将我推向正确的方向吗?

已经谢谢了!-M

标签: pythonnumpyfilteringconditional-statements

解决方案


德摩根定律not (p and q) == (not p) *or* (not q)。无论如何,numpy 中的 not 运算符是~这样的

 ~((test[:, 0] >= 30) & (test[:, 1] <= 2)) == ((test[:, 0] < 30) | (test[:, 1] > 2))

要么会做你想做的事,例如

test1 = test[~((test[:, 0] >= 30) & (test[:, 1] <= 2))]

推荐阅读