[Numpy-discussion] extracting values from an array

Eric Emsellem emsellem at obs.univ-lyon1.fr
Thu Dec 28 09:33:35 CST 2006


Hi,

I have a simple problem of extracting a subarray from a bigger one, for
which I don't find an elegant/easy solution.
I tried using searchsorted, or other tricks but I always end up with
many "if" statements, testing all cases
(also because searchsorted does not work on arrays which are sorted in
decreasing order). There must be an elegant solution but I cannot find it.

==> I have one array of floats which has e.g. regular steps (as produced
by arange) but can either be decreasing or increasing as for:
x = arange(0.,1.,0.1)
## or
x = arange(0.,-1.,-0.1)

I also have another "data" y array, which has the same length than x.

And I would like to extract from these arrays the subarrays,
corresponding to the range x1 -- x2, going from x1, to x2.
The output array should have its first element starting from the element
in x closest to x1 (and in the range defined by x1, x2), and then going
towards x2, for all cases (decreasing or increading order for x, and
x1>=x2 or x1<=x2).

So here is the output I would like to get in 3 different simple examples:

### Increasing order in x, and x1 <= x2 :
x = arange(0.,1.,0.1)
x1 = 0.1
x2 = 0.55
### the output I would like is simply: array([ 0.1, 0.2, 0.3, 0.4,
0.5])

### decreasing order in x, and x1 <= x2 :
x = arange(0.,-1.,-0.1)
x1 = -0.55
x2 = -0.1
### I would like is then: array([ -0.5, -0.4, -0.3, -0.2, -0.1])

### decreasing order in x, and x1 >= x2 :
x = arange(0.,-1.,-0.1)
x1 = -0.1
x2 = -0.55
### I would like is then: array([ -0.1, -0.2, -0.3, -0.4, -0.5])

etc....

And it should work if both x1, and x2 are outside the given range
provided in x (output should be an empty array)
Note that I also need to extract the corresponding subarray from the
data array (same indices as the one I extract from x).

I hope this is clear. It is a very simple problem but I cannot see a
simple solution without involving lots of stupid "if". It would be great
if these "if" statements were hidden in some efficient numpy
tricks/functions.

thanks for any input.

Eric


More information about the Numpy-discussion mailing list