如何在给定条件下选择数组的元素? [英] How do I select elements of an array given condition?
本文介绍了如何在给定条件下选择数组的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个 numpy 数组 x = [5, 2, 3, 1, 4, 5]
, y = ['f', 'o', 'o','b', 'a', 'r']
.我想选择y
中x
中大于1小于5的元素对应的元素.
我试过了
x = 数组([5, 2, 3, 1, 4, 5])y = 数组(['f','o','o','b','a','r'])输出 = y[x >1 &×<5] # 期望的输出是 ['o','o','a']
但这不起作用.我该怎么做?
解决方案
如果您添加括号,您的表达式将起作用:
<预><代码>>>>y[(1 < x) &(x <5)]数组(['o', 'o', 'a'],dtype='|S1')Suppose I have a numpy array x = [5, 2, 3, 1, 4, 5]
, y = ['f', 'o', 'o', 'b', 'a', 'r']
. I want to select the elements in y
corresponding to elements in x
that are greater than 1 and less than 5.
I tried
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']
but this doesn't work. How would I do this?
解决方案
Your expression works if you add parentheses:
>>> y[(1 < x) & (x < 5)]
array(['o', 'o', 'a'],
dtype='|S1')
这篇关于如何在给定条件下选择数组的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文