【问题标题】:Issue when filtering rows of numpy array by multiple conditions按多个条件过滤 numpy 数组行时的问题
【发布时间】:2018-11-23 01:34:27
【问题描述】:

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

只是为了让您了解数据:

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

【问题讨论】:

  • A和B的反义词是notA notB,>=的反义词是test2 = test[(test[:, 0] < 30) | (test[:, 1] > 2)] 应该完成这项工作。
  • 这很清楚,谢谢!

标签: python numpy filtering conditional-statements


【解决方案1】:

De morgans lawnot (p and q) == (not p) *or* (not q)。无论如何,numpy is ~ 中的 not 运算符所以

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

要么做你想做的事,例如

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

【讨论】:

  • 谢谢!现在我觉得真的很愚蠢,因为我之前在我的代码中甚至使用了~。但是感谢您给我一些关于德摩根定律的背景信息!
猜你喜欢
  • 2015-06-12
  • 2021-10-20
  • 2016-12-19
  • 1970-01-01
  • 2020-08-05
  • 1970-01-01
  • 1970-01-01
  • 2017-10-03
相关资源
最近更新 更多