numpy:按多种条件过滤行吗? [英] Numpy: Filtering rows by multiple conditions?

查看:152
本文介绍了numpy:按多种条件过滤行吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为meta的二维NumPy数组,具有3列..我想要做的是:

I have a two-dimensional numpy array called meta with 3 columns.. what I want to do is :

  1. 检查前两列是否为零
  2. 检查第三列是否小于X
  3. 仅返回符合条件的行

我成功了,但是解决方案似乎非常人为:

I made it work, but the solution seem very contrived :

meta[ np.logical_and( np.all( meta[:,0:2] == [0,0],axis=1 ) , meta[:,2] < 20) ]

您能想到更清洁的方式吗?似乎很难同时具有多个条件;(

Could you think of cleaner way ? It seem hard to have multiple conditions at once ;(

谢谢

对不起,我第一次复制错误的表达式...已更正.

Sorry first time I copied the wrong expression... corrected.

推荐答案

您可以在一个切片中使用多个过滤器,如下所示:

you can use multiple filters in a slice, something like this:

x = np.arange(90.).reshape(30, 3)
#set the first 10 rows of cols 1,2 to be zero
x[0:10, 0:2] = 0.0
x[(x[:,0] == 0.) & (x[:,1] == 0.) & (x[:,2] > 10)]
#should give only a few rows
array([[  0.,   0.,  11.],
       [  0.,   0.,  14.],
       [  0.,   0.,  17.],
       [  0.,   0.,  20.],
       [  0.,   0.,  23.],
       [  0.,   0.,  26.],
       [  0.,   0.,  29.]])

这篇关于numpy:按多种条件过滤行吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆