如何在 numpy 中找到给定 y 的 x 或反之亦然?

Kit*_*Kit 4 search numpy numerical-methods

例如,我有以下数组:

x = [0, 1, 2, 3, 4.5, 5]
y = [2, 8, 3, 7,   8, 1]
Run Code Online (Sandbox Code Playgroud)

我希望能够执行以下操作x

>>> what_is_y_when_x_is(2)
(2, 3)
>>> what_is_y_when_x_is(3.1) # Perhaps set rules to round to nearest (or up or down)
(3, 7)
Run Code Online (Sandbox Code Playgroud)

另一方面,当给出y

>>> what_is_x_when_y_is(2)
(0, 2)
>>> what_is_x_when_y_is(max(y))
([1, 4.5], 8)
Run Code Online (Sandbox Code Playgroud)

这个问题的具体情况

我可以绘制与使用封闭分析函数的y对比结果x,只需调用foo_function(x). 但是,我正在运行数值模拟,其数据图没有闭合解析解。

尝试的解决方案

我之前解决过类似的问题,大致是这样处理的:

what_is_y_when_x_is(some_x)

  1. 在数组x中搜索some_x.
  2. 获取其索引,i.
  3. 捡起y[i]

问题

有一个更好的方法吗?也许是内置numpy函数或更好的算法?

Bi *_*ico 5

您应该查看 numpy.searchsorted 和 numpy.interp。这两个看起来都可以成功。这是一个例子:

import numpy as np
x = 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 methods
order = 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)
# 3
print interp_x_from_y(1.5, x, y)
# 2.5
Run Code Online (Sandbox Code Playgroud)