Numpy:按多个条件过滤行?
问题描述
我有一个名为 meta
的二维 numpy 数组,它有 3 列.我想要做的是:
I have a two-dimensional numpy array called meta
with 3 columns.. what I want to do is :
- 检查前两列是否为零
- 检查第三列是否小于 X
- 只返回符合条件的行
我做到了,但解决方案似乎很做作:
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.]])
相关文章