Using multiple hints for arrays in python

I have a simple question on how to use multiple pointers for an array or rec.array. In particular, I want to select the cell (s) in an array that matches several conditions. For instance:

import numpy as np test = np.ones(5) test_rec = test.view(recarray) test_rec.age = np.array([0,1,2,1,4]) test_rec.sex = np.array([0,1,1,0,0]) 

I want to isolate test_rec where test_rec age is 1 and test_rec.sex is 1, i.e.:

 test_rec[test_rec.age==1 and test_rec.sex==1] 

Unfortunately this does not work.

+4
source share
2 answers

use logical_and () or bitwise_and (), and you can use the operator to execute bitwise_and ():

 test_rec[(test_rec.age==1) & (test_rec.sex==1)] 

parentheses are important because priority is lower than ==.

+1
source
 age_is_one = test_rec.age == 1 sex_is_one = test_rec.sex == 1 age_and_sex = numpy.logical_and(age_is_one, sex_is_one) indices = numpy.nonzero(age_and_sex) test_rec[indices] 

Cm:

numpy logical operations

numpy.nonzero

+1
source

All Articles