首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在给定条件下选择数组中的元素?

如何在给定条件下选择数组中的元素?
EN

Stack Overflow用户
提问于 2010-06-13 07:28:06
回答 6查看 276.2K关注 0票数 178

假设我有一个数值数组x = [5, 2, 3, 1, 4, 5]y = ['f', 'o', 'o', 'b', 'a', 'r']。我想选择与x中大于1和小于5的元素相对应的y中的元素。

我试过了

x = array([5, 2, 3, 1, 4, 5])
y = array(['f','o','o','b','a','r'])
output = y[x > 1 & x < 5] # desired output is ['o','o','a']

但这不管用。我该怎么做呢?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2010-06-13 08:50:33

如果添加圆括号,则表达式有效:

>>> y[(1 < x) & (x < 5)]
array(['o', 'o', 'a'], 
      dtype='|S1')
票数 250
EN

Stack Overflow用户

发布于 2013-09-06 03:23:44

IMO OP实际上并不想要np.bitwise_and() (aka &),但实际上想要np.logical_and(),因为它们比较的是逻辑值,例如TrueFalse -请参阅logical vs. bitwise上的这篇文章以了解其中的区别。

>>> x = array([5, 2, 3, 1, 4, 5])
>>> y = array(['f','o','o','b','a','r'])
>>> output = y[np.logical_and(x > 1, x < 5)] # desired output is ['o','o','a']
>>> output
array(['o', 'o', 'a'],
      dtype='|S1')

实现这一点的等效方法是通过适当设置axis参数来使用np.all()

>>> output = y[np.all([x > 1, x < 5], axis=0)] # desired output is ['o','o','a']
>>> output
array(['o', 'o', 'a'],
      dtype='|S1')

从数字上看:

>>> %timeit (a < b) & (b < c)
The slowest run took 32.97 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 1.15 µs per loop

>>> %timeit np.logical_and(a < b, b < c)
The slowest run took 32.59 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 1.17 µs per loop

>>> %timeit np.all([a < b, b < c], 0)
The slowest run took 67.47 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 5.06 µs per loop

所以使用np.all()比较慢,但是&logical_and差不多。

票数 40
EN

Stack Overflow用户

发布于 2014-11-19 00:03:18

在@J.F. Sebastian和@Mark Mikofski的回答中添加一个细节:

如果想要获得相应的索引(而不是数组的实际值),可以使用以下代码:

要满足多个(全部)条件:

select_indices = np.where( np.logical_and( x > 1, x < 5) )[0] #   1 < x <5

用于满足多个(或)条件:

select_indices = np.where( np.logical_or( x < 1, x > 5 ) )[0] # x <1 or x >5
票数 24
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3030480

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档