5

I am using Python. How to make a subselection of a vector, based on the values of two other vectors with the same length?

For example this three vectors

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)

I want to do something like this:

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()

In Matlab, I would use:

elem  = find(c2==2 & c3==3);
c1sel = c1(elem);

How to do this in Python?

David Zwicker
  • 23,581
  • 6
  • 62
  • 77
vincentv
  • 175
  • 2
  • 6

3 Answers3

5

You can use numpy.logical_and:

>>> c1[np.logical_and(c2==2, c3==3)]
array([9, 5])
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • As far as I can see, this does not work for more than two conditions. For three or more, I use the solution of mskimm. – vincentv Apr 17 '14 at 14:42
3

Alternatively, try

>>> c1[(c2==2) & (c3==3)]
array([9, 5])

cf) By Python Operator Precedence, the priority of & is upper than ==. See the follow results.

>>> 1 == 1 & 2 == 2
False

>>> (1 == 1) & (2 == 2)
True
emesday
  • 6,078
  • 3
  • 29
  • 46
1

You have to keep each of your conditions inside parenthesis:

In []: c1[(c2 == 2) & (c3 == 3)]
Out[]: array([9, 5])
logc
  • 3,813
  • 1
  • 18
  • 29