用逻辑运算符索引numpy数组 [英] indexing numpy array with logical operator

查看:295
本文介绍了用逻辑运算符索引numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维的numpy数组,例如:

I have a 2d numpy array, for instance as:

import numpy as np
a1 = np.zeros( (500,2) )

a1[:,0]=np.arange(0,500)
a1[:,1]=np.arange(0.5,1000,2)
# could be also read from txt

然后,我要选择与符合条件(例如范围(l1,l2)中包含的所有值a1 [:,1])的切片相对应的索引:

then I want to select the indexes corresponding to a slice that matches a criteria such as all the value a1[:,1] included in the range (l1,l2):

l1=20.0; l2=900.0; #as example

我想用一个简洁的表达来做.但是,都没有:

I'd like to do in a condensed expression. However, neither:

np.where(a1[:,1]>l1 and a1[:,1]<l2)

(它给出ValueError并建议使用np.all,在这种情况下我不清楚);都不:

(it gives ValueError and it suggests to use np.all, which it is not clear to me in such a case); neither:

np.intersect1d(np.where(a1[:,1]>l1),np.where(a1[:,1]<l2))

正在工作(它给出了不可散列的类型:"numpy.ndarray")

is working (it gives unhashable type: 'numpy.ndarray')

然后我的想法是使用这些索引来映射另一个大小为(500,n)的数组.

My idea is then to use these indexes to map another array of size (500,n).

是否有任何合理的方式来选择索引?或者:在这种情况下是否需要使用一些口罩?

Is there any reasonable way to select indexes in such way? Or: is it necessary to use some mask in such case?

推荐答案

这应该有效

np.where((a1[:,1]>l1) & (a1[:,1]<l2))

np.where(np.logical_and(a1[:,1]>l1, a1[:,1]<l2))

这篇关于用逻辑运算符索引numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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