score:0

If interpolation for visualization is the goal, simply plotting the function does the trick. Numpy draws lines between data points, which is equivalent to linear interpolation.

However, if you want to work with the interpolated values you can use np.interp for linear interpolation or some function from scipy.interpolate for any type of interpolation. Finally, you can perform nearest neighbor interpolation by simply rounding the index.

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 4, 11)      # [ 0.   0.4  0.8  1.2  1.6  2.   2.4  2.8  3.2  3.6  4. ]
y = np.array([0, 1, 2, 3, 3, 1, -1, -4, -5, -6, -7])

xi = np.linspace(0, 4, 1000)

# a) nearest neighbor rounding
dx = x[1] - x[0]
i = np.round(xi/dx).astype(dtype=int)
y1 = y[i]

# b) linear interpolation
y2 = np.interp(xi, x, y)

plt.plot(x, y, '.', label='original points')
plt.plot(xi, y1, label='rounding (nearest neighbor)')
plt.plot(xi, y2, label='linear interpolation')
plt.legend(loc='best')
plt.show()

enter image description here

score:0

The solution given as comment by @ali_m works well :

np.interp(1.2, x, y)    # 3.0
np.interp(2.3, x, y)    # -0.5
np.interp(2.4, x, y)    # -1

Related Query