4

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]

Unfortunately, this does not work.

1
  • It appears you are incorrectly creating your recarray. Commented Aug 4, 2011 at 5:47

2 Answers 2

1

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 ==.

Sign up to request clarification or add additional context in comments.

Comments

1
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.