Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make subset of array, based on values of two other arrays in 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?

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?

like image 632
vincentv Avatar asked Apr 16 '14 12:04

vincentv


People also ask

How do you create a subset of an array in Python?

To get the subarray we can use slicing to get the subarray. Step 1: Run a loop till length+1 of the given list. Step 2: Run another loop from 0 to i. Step 3: Slice the subarray from j to i.

Can you divide an array by another array in Python?

Array element from first array is divided by elements from second element (all happens element-wise). Both arr1 and arr2 must have same shape and element in arr2 must not be zero; otherwise it will raise an error. Parameters : arr1 : [array_like]Input array or object which works as dividend.

How do you combine two arrays in Python?

How to concatenate NumPy arrays in Python? You can use the numpy. concatenate() function to concat, merge, or join a sequence of two or multiple arrays into a single NumPy array. Concatenation refers to putting the contents of two or more arrays in a single array.

Can you divide two arrays in Python?

divide is with two same-sized arrays (i.e., arrays with exactly the same number of rows and columns). If the two input arrays have the same shape, then Numpy divide will divide the elements of the first array by the elements of the second array, in an element-wise fashion.


3 Answers

You can use numpy.logical_and:

>>> c1[np.logical_and(c2==2, c3==3)]
array([9, 5])
like image 200
Ashwini Chaudhary Avatar answered Oct 13 '22 23:10

Ashwini Chaudhary


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
like image 25
emeth Avatar answered Oct 13 '22 21:10

emeth


You have to keep each of your conditions inside parenthesis:

In []: c1[(c2 == 2) & (c3 == 3)]
Out[]: array([9, 5])
like image 1
logc Avatar answered Oct 13 '22 22:10

logc