interp1d 给 nan 外推

interp1d gives nan with extrapolation

我正在尝试使用 interp1d 和外推来插入具有 nan 值的数据:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(11)
y = np.array([np.nan, np.nan, np.nan, 1, np.nan, np.nan, 9, 7, 6, np.nan, np.nan])

f = interp1d(x, y, axis=-1, kind='linear', fill_value='extrapolate')
print(f(8.8))

plt.scatter(x, y, label='data')
plt.axvline(8.8, c='red', label='interpolation position')
plt.legend()

但是,结果是 NaN。

即使我选择x的一个子集,它仍然是nan:

f = interp1d(x[6:], y[6:], axis=-1, kind='linear', fill_value='extrapolate')
print(f(8.8))

plt.scatter(x[6:], y[6:], label='data')
plt.axvline(8.8, c='red', label='interpolation position')
plt.legend()

您需要在插值之前删除 nans:

valid = np.nonzero(~np.isnan(y))
f = interp1d(x[valid], y[valid], axis=-1, kind='linear', fill_value='extrapolate')

print(f(8.8))
# 5.199999999999999