How do I find x given y or vice versa in numpy? How do I find x given y or vice versa in numpy? numpy numpy

How do I find x given y or vice versa in numpy?


You should look at numpy.searchsorted and also numpy.interp. Both of those look like they might do the trick. Here is an example:

import numpy as npx = np.array([0, 1, 2, 3, 4.5, 5])y = np.array([2, 8, 3, 7,   8, 1])# y should be sorted for both of these methodsorder = y.argsort()y = y[order]x = x[order]def what_is_x_when_y_is(input, x, y):    return x[y.searchsorted(input, 'left')]def interp_x_from_y(input, x, y):    return np.interp(input, y, x)print what_is_x_when_y_is(7, x, y)# 3print interp_x_from_y(1.5, x, y)# 2.5


You could use the bisect module for this. This is pure python - no numpy here:

>>> x = [0, 1, 2, 3, 4.5, 5]>>> y = [2, 8, 3, 7,   8, 1]>>> x_lookup = sorted(zip(x, y))>>> y_lookup = sorted(map(tuple, map(reversed, zip(x, y))))>>> >>> import bisect>>> def pair_from_x(x):...    return x_lookup[min(bisect.bisect_left(x_lookup, (x,)), len(x_lookup)-1)]... >>> def pair_from_y(y):...    return tuple(reversed(y_lookup[min(bisect.bisect_left(y_lookup, (y,)), len(y_lookup)-1)]))... 

And some examples of using it:

>>> pair_from_x(0)(0, 2)>>> pair_from_x(-2)(0, 2)>>> pair_from_x(2)(2, 3)>>> pair_from_x(3)(3, 7)>>> pair_from_x(7)(5, 1)>>> >>> pair_from_y(0)(5, 1)>>> pair_from_y(1)(5, 1)>>> pair_from_y(3)(2, 3)>>> pair_from_y(4)(3, 7)>>> pair_from_y(8)(1, 8)


The way you described is, as far as I'm considered, a good way. I'm not sure if you are, but I think you could use the .index(...) method on your array:

>>> li['I', 'hope', 'this', 'answer', 'helps', 'you']>>> li.index("hope")1

Other than that, you might want to consider one array op "Points" which have an x and a y, though I'm not sure if this is possible of course. That way you won't have to keep two arrays in sync (same number of elements).