vin*_*ntv 5 python boolean-logic numpy subset
我正在使用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)
Run Code Online (Sandbox Code Playgroud)
我想做这样的事情:
elem = (c2==2 and c3==3)
c1sel = c1[elem]
Run Code Online (Sandbox Code Playgroud)
但第一个语句导致错误:
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()
Run Code Online (Sandbox Code Playgroud)
在Matlab中,我会使用:
elem = find(c2==2 & c3==3);
c1sel = c1(elem);
Run Code Online (Sandbox Code Playgroud)
如何在Python中执行此操作?
你可以使用numpy.logical_and:
>>> c1[np.logical_and(c2==2, c3==3)]
array([9, 5])
Run Code Online (Sandbox Code Playgroud)