Python에서 '가장 가까운' 방법을 사용한 외삽
-
20-12-2019 - |
문제
다음 Matlab 문에 해당하는 Python을 찾고 있습니다.
vq interp1(x,y, xq,'nearest','extrap')
마치 interp(xq, x, y)
선형 보간/외삽에 완벽하게 작동합니다.
나도 살펴봤어
F = scipy.interpolate.interp1d(x, y, kind='nearest')
가장 가까운 방법에서는 완벽하게 작동하지만 외삽을 수행하지는 않습니다.
내가 간과한 다른 것이 있습니까?감사해요.
해결책
가장 가까운 보간법을 사용하여 외삽하는 선형 보간법의 경우 다음을 사용하십시오. numpy.interp
.기본적으로 이 작업을 수행합니다.
예를 들어:
yi = np.interp(xi, x, y)
그렇지 않고 설명대로 가장 가까운 보간을 원하는 경우 짧지만 비효율적인 방법으로 수행할 수 있습니다.(원한다면 이것을 한 줄로 만들 수 있습니다)
def nearest_interp(xi, x, y):
idx = np.abs(x - xi[:,None])
return y[idx.argmin(axis=1)]
또는 다음을 사용하여 보다 효율적인 방법으로 searchsorted
:
def fast_nearest_interp(xi, x, y):
"""Assumes that x is monotonically increasing!!."""
# Shift x points to centers
spacing = np.diff(x) / 2
x = x + np.hstack([spacing, spacing[-1]])
# Append the last point in y twice for ease of use
y = np.hstack([y, y[-1]])
return y[np.searchsorted(x, xi)]
차이점을 설명하기 위해 numpy.interp
위의 가장 가까운 보간 예는 다음과 같습니다.
import numpy as np
import matplotlib.pyplot as plt
def main():
x = np.array([0.1, 0.3, 1.9])
y = np.array([4, -9, 1])
xi = np.linspace(-1, 3, 200)
fig, axes = plt.subplots(nrows=2, sharex=True, sharey=True)
for ax in axes:
ax.margins(0.05)
ax.plot(x, y, 'ro')
axes[0].plot(xi, np.interp(xi, x, y), color='blue')
axes[1].plot(xi, nearest_interp(xi, x, y), color='green')
kwargs = dict(x=0.95, y=0.9, ha='right', va='top')
axes[0].set_title("Numpy's $interp$ function", **kwargs)
axes[1].set_title('Nearest Interpolation', **kwargs)
plt.show()
def nearest_interp(xi, x, y):
idx = np.abs(x - xi[:,None])
return y[idx.argmin(axis=1)]
main()
다른 팁
SCIPY 버전 (적어도 V0.19.1 +) 버전에서 scipy.interpolate.interp1d
는 fill_value = “extrapolate”
옵션을 갖습니다.
예 :
import pandas as pd
>>> s = pd.Series([1, 2, 3])
Out[1]:
0 1
1 2
2 3
dtype: int64
>>> t = pd.concat([s, pd.Series(index=s.index + 0.1)]).sort_index()
Out[2]:
0.0 1.0
0.1 NaN
1.0 2.0
1.1 NaN
2.0 3.0
2.1 NaN
dtype: float64
>>> t.interpolate(method='nearest')
Out[3]:
0.0 1.0
0.1 1.0
1.0 2.0
1.1 2.0
2.0 3.0
2.1 NaN
dtype: float64
>>> t.interpolate(method='nearest', fill_value='extrapolate')
Out[4]:
0.0 1.0
0.1 1.0
1.0 2.0
1.1 2.0
2.0 3.0
2.1 3.0
dtype: float64
. 제휴하지 않습니다 StackOverflow