如何选择给定条件的数组元素? [英] 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的元素相对应的元素.
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.
我尝试过
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屋!
查看全文