Using multiple indicies for arrays in python
I have a simple question about how to use multiple indicies for an array or rec.array. More specifically, I want to isolate the cell(s) in an array which meet multiple stipulations. For example:
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, ie:
test_rec[test_rec.age==1 and test_rec.sex==1]
Unf开发者_StackOverflowortunately, this does not work.
use logical_and() or bitwise_and(), and you can use & operator to do bitwise_and():
test_rec[(test_rec.age==1) & (test_rec.sex==1)]
the brackets is important, because the precedence of & is lower then ==.
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]
See:
numpy logical operations
numpy.nonzero
精彩评论