0

I have a numpy structured array with one of the columns called 'time' I want to restrict my data where the 'time' column is in a certain range. I tried this:

time_restricted_data = Data[ (Data['time'] > 0.6) & (Data['time'] < 0.7) ]

But that returned all the data where Data['time'] > 0.6.

Any suggestions?

3
  • I'm a little confused what Data is...you're indexing it with a string and then later your indexing it with something which (probably) isn't a string. Could provide a little more context code in your example? Commented May 1, 2012 at 14:55
  • @mgilson numpy arrays can be indexed by arrays of bools, the effect of which is to extract a subset of the array corresponding to the 'true' bool elements. I'm not familiar with structured arrays (which can be indexed by strings) but I have had problems indexing a normal array A using a bool array B, in the case where B needs one or more dimensions expanded to fit the shape of A. Commented May 1, 2012 at 15:03
  • @greggo -- I understand that numpy arrays can be indexed by arrays of bools. I just think that we need to know how he has it set up so that Data can be indexed by a string ("time") and (presumably) an array of bools at the same time...It's possible that he just needs to do time_restricted_data = Data["time"][...] (e.g. if Data is really a dict holding numpy arrays and he forgot to mention that...) Commented May 1, 2012 at 15:07

1 Answer 1

1

Something is wrong in your example, i.e. I can't confirm it, and I think what you wrote should work as expected:

In [19]: Data = np.zeros(100,dtype=[('time', np.float), ('y',np.float)])

In [20]: Data['y'] = np.random.uniform(size=100)

In [21]: Data['time'] = np.random.uniform(size=100)

In [22]: print Data[ (Data['time'] > 0.6) & (Data['time'] < 0.7) ]
[(0.6309334093696576, 0.5898588768194092)
 (0.6026040512366535, 0.4260650141076221)
 (0.6587399844526572, 0.033397798015253444)
 (0.6863639946779522, 0.67002523603246)
 (0.6522035987367735, 0.948019085443445)
 (0.6809894254849801, 0.5131390279565994)
 (0.6311277013562147, 0.5746610745753917)
 (0.6324174554481182, 0.8587836614681397)
 (0.6542221804687635, 0.9706926940115863)
 (0.671321726341415, 0.7446681474117195)]
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this explains how you can index a np array by a string and boolean values -- I'd never seen this done before, although it seems like it could be quite useful.
Well I tried again what I had tried before and it works. Your solution is correct. I must have had a typo somewhere before.

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.