zxdawn
zxdawn

Reputation: 1015

interp1d gives nan with extrapolation

I'm trying to interpolate data that has nan values using interp1d with extrapolation:

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()

But, the result is NaN.

example

Even if I pick a subset of x, it is still 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()

example2

Upvotes: 1

Views: 922

Answers (1)

Stef
Stef

Reputation: 30639

You need to remove the nans before interpolating:

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

Upvotes: 4

Related Questions