python - 按多个条件过滤 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
解决方案
德摩根定律: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))]
推荐阅读
- python - 遍历嵌套 JSON 的迭代方式?
- plotly - Plotly-将x轴放在前面
- apache-spark - 火花历史服务器在火花提交期间崩溃,并且在历史服务器活动时火花提交被杀死(独立集群)
- javascript - Autofill extension that fills form without form tags
- django - 异常类型:DoesNotExist | 配置文件匹配查询不存在
- javascript - 有没有办法让firebase触发器在更新多个子集合时触发?
- stata - Null hypothesis testing
- jquery - Error Internal Server Error blueimp jquery file upload
- ffmpeg - 在 discord.py 中使用 ffmpeg 库时出现 OpusError
- android - WebService 请求从 Android 代码转码到 Swift 代码