1

Very quick question, can't find an answer with these keywords. What is a better way of doing the following?

t = linspace(0,1000,300)    
x0 = generic_function(t)

x1 = x0[x0>0.8]
t1 = t[t>t[len(x0)-len(x1)-1]]

The operation I'm using @t1 strikes me as very un-pythonic and inefficient. Any pointers?

1
  • not to mention it only works because my values increase monotonically Commented Jul 30, 2012 at 23:06

1 Answer 1

2

IIUC, you can simply reuse the cut array. For example:

>>> from numpy import arange, sin
>>> t = arange(5)
>>> t
array([0, 1, 2, 3, 4])
>>> y = sin(t)
>>> y
array([ 0.        ,  0.84147098,  0.90929743,  0.14112001, -0.7568025 ])

As you've already done, you can make a bool array:

>>> y > 0.8
array([False,  True,  True, False, False], dtype=bool)

and then you can use this to filter both t and y:

>>> t[y > 0.8]
array([1, 2])
>>> y[y > 0.8]
array([ 0.84147098,  0.90929743])

No use of len or assumptions about monotonicity involved.

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

2 Comments

actually, I have a follow-up question. what do you call that? filtering, cutting or slicing?
@RodericDay: I'd simply call it "indexing", only with an array of bools. The numpy docs call it advanced indexing. Slicing is the stuff with colons, e.g. t[3:4, 2:30:5], etc.

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.