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)
.
それ以外の場合は、どこにでも最も近い補間が必要な場合は、短くても非効率的な方法で行うことができます。(必要な場合は、これを1つのライナーにすることができます)
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