根据两个数组的值在Python中创建数组子集
我在用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中该怎么做呢?
3 个回答
1
你需要把每一个条件放在括号里:
In []: c1[(c2 == 2) & (c3 == 3)]
Out[]: array([9, 5])
3
另外,你可以试试
>>> c1[(c2==2) & (c3==3)]
array([9, 5])
根据Python运算符优先级,&
的优先级比==
高。看看下面的结果。
>>> 1 == 1 & 2 == 2
False
>>> (1 == 1) & (2 == 2)
True
5
你可以使用 numpy.logical_and
这个函数:
>>> c1[np.logical_and(c2==2, c3==3)]
array([9, 5])