根据Python中其他两个数组的值制作数组的子集 [英] Make subset of array, based on values of two other arrays in Python
本文介绍了根据Python中其他两个数组的值制作数组的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Python.如何基于其他两个相同长度的向量的值对向量进行子选择?
I am using Python. How to make a subselection of a vector, based on the values of two other vectors with the same length?
例如这三个向量
c1 = np.array([1,9,3,5])
c2 = np.array([2,2,3,2])
c3 = np.array([2,3,2,3])
c2==2
array([ True, True, False, True], dtype=bool)
c3==3
array([False, True, False, True], dtype=bool)
我想做这样的事情:
elem = (c2==2 and c3==3)
c1sel = c1[elem]
但是第一条语句导致错误:
But the first statement results in an error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous.
Use a.any() or a.all()
在Matlab中,我将使用:
In Matlab, I would use:
elem = find(c2==2 & c3==3);
c1sel = c1(elem);
如何在Python中执行此操作?
How to do this in Python?
推荐答案
您可以使用 numpy.logical_and
:
You can use numpy.logical_and
:
>>> c1[np.logical_and(c2==2, c3==3)]
array([9, 5])
这篇关于根据Python中其他两个数组的值制作数组的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文