我正在使用Python。如何基于其他两个具有相同长度的向量的值对向量进行子选择?
例如这三个向量
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]
但是第一条语句导致错误:
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中,我将使用:
elem = find(c2==2 & c3==3);
c1sel = c1(elem);
如何在Python中做到这一点?
最佳答案
您可以使用 numpy.logical_and
:
>>> c1[np.logical_and(c2==2, c3==3)]
array([9, 5])