我在 python 中有一个包含 2 列的数据框。我想输入一列的数据框并获取第二列的值。有时这些值可以是精确的,但它们也可以是两行之间的值。
我有这个示例数据框:
x y
0 0 0
1 10 100
2 20 200
Run Code Online (Sandbox Code Playgroud)
如果我用 x 的值检查数据帧,我想找到 y 的值。例如,如果我在数据框中输入值为 10,则得到的值为 100。但如果我检查 15,则需要在 y 的两个值之间进行插值。有什么函数可以做到吗?
numpy.interp可能是线性插值最简单的方法:
def interpolate(xval, df, xcol, ycol):
# compute xval as the linear interpolation of xval where df is a dataframe and
# df.x are the x coordinates, and df.y are the y coordinates. df.x is expected to be sorted.
return np.interp([xval], df[xcol], df[ycol])
Run Code Online (Sandbox Code Playgroud)
根据您的示例数据,它给出:
>>> interpolate(10, df, 'x', 'y')
>>> 100.0
>>> interpolate(15, df, 'x', 'y')
>>> 150.0
Run Code Online (Sandbox Code Playgroud)
你甚至可以直接这样做:
>>> np.interp([10, 15], df.x, df.y)
array([100., 150.])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8622 次 |
| 最近记录: |