NumPy np.interp: Interpolation Explained with Python Examples

Interpolation is one of those everyday data tasks that quietly powers charts, sensor dashboards, simulations, financial models, and scientific analysis. In Python, NumPy provides a fast and convenient function for one-dimensional linear interpolation: np.interp(). If you have values measured at known points and want to estimate values between them, this function is often the simplest tool for the job.

TLDR: np.interp() estimates unknown y values for given x positions using straight-line interpolation between known data points. For example, if a temperature sensor records 20°C at minute 0 and 30°C at minute 10, np.interp(5, [0, 10], [20, 30]) returns 25. In a dashboard that samples server CPU usage every 60 seconds, interpolation can fill intermediate 10-second chart points, increasing visual smoothness by 500% without collecting more raw data. It is fast, readable, and ideal when your data changes reasonably smoothly between observations.

What Is Linear Interpolation?

Linear interpolation means estimating a value between two known points by drawing a straight line between them. Suppose you know that a car traveled 0 kilometers at 0 minutes and 100 kilometers at 60 minutes. If speed was constant, the distance at 30 minutes would be halfway between: 50 kilometers.

This idea is simple, but powerful. Many real-world datasets are collected at fixed intervals, yet analysis or visualization often needs values at different intervals. Rather than leaving gaps, interpolation provides reasonable estimates.

The Basic Syntax of np.interp()

The core syntax is:

numpy.interp(x, xp, fp, left=None, right=None, period=None)

Here is what the main parameters mean:

  • x: The x-coordinate or coordinates where you want estimated values.
  • xp: The known x-coordinates of your data points. These should be increasing.
  • fp: The known y-values that correspond to xp.
  • left: Optional value returned when x is smaller than the first xp.
  • right: Optional value returned when x is larger than the last xp.
  • period: Optional period for circular data, such as angles.

The most common use only needs the first three arguments.

A Simple Python Example

Let’s estimate a temperature reading between two recorded measurements:

import numpy as np

time = [0, 10]
temperature = [20, 30]

estimate = np.interp(5, time, temperature)
print(estimate)

The output is:

25.0

Since minute 5 is exactly halfway between minute 0 and minute 10, the estimated temperature is halfway between 20 and 30.

Interpolating Multiple Values at Once

np.interp() becomes especially useful when you pass an array of new x-values. Imagine you recorded sales data once per week but want estimated values for specific days.

import numpy as np

days_known = [0, 7, 14, 21]
sales_known = [100, 150, 130, 200]

days_to_estimate = [3, 10, 17, 20]
estimated_sales = np.interp(days_to_estimate, days_known, sales_known)

print(estimated_sales)

Possible output:

[121.42857143 141.42857143 160.         190.        ]

This means the estimated sales on day 3 are about 121.43, while on day 20 they are estimated at 190. The function returns a NumPy array, which makes it convenient for further calculations or plotting.

How np.interp() Works Internally

For each requested x-value, NumPy finds the two known x-values surrounding it. Then it calculates where the requested point lies between them and applies the same proportion to the y-values.

Conceptually, if you have two points:

(x1, y1) and (x2, y2)

The interpolated value at x is calculated as:

y = y1 + (x - x1) * (y2 - y1) / (x2 - x1)

You do not need to write this formula yourself in most cases, but understanding it helps you know what interpolation is actually doing. It is not predicting trends using machine learning, and it is not fitting a complex curve. It is simply drawing straight lines between known data points.

Handling Values Outside the Known Range

By default, if the requested x-value is below the first known x-value, np.interp() returns the first y-value. If it is above the last known x-value, it returns the last y-value.

import numpy as np

x_known = [10, 20, 30]
y_known = [100, 200, 300]

print(np.interp(5, x_known, y_known))
print(np.interp(40, x_known, y_known))

The output is:

100.0
300.0

You can customize this behavior with left and right:

result = np.interp(
    [5, 15, 40],
    x_known,
    y_known,
    left=-1,
    right=999
)

print(result)

Output:

[ -1. 150. 999.]

This is useful when out-of-range estimates should be clearly marked rather than silently replaced with boundary values.

Common Use Cases

np.interp() is helpful in many practical situations, including:

  • Sensor data: Filling missing temperature, pressure, or motion readings between timestamps.
  • Finance: Estimating values between known interest rates, stock prices, or yield curve points.
  • Scientific experiments: Converting irregular measurements into evenly spaced samples.
  • Game development: Smoothing movement or transitions between key positions.
  • Data visualization: Creating smoother line charts from sparse measurements.

For example, a weather station might record humidity every 15 minutes, but a web chart displays points every 5 minutes. Interpolation can create two estimated points between each real measurement, making the chart appear smoother while preserving the original trend.

Important Requirements and Pitfalls

Although np.interp() is easy to use, there are a few important details to remember.

  • xp should be increasing: The known x-values should be sorted from smallest to largest. If they are not, results may be incorrect.
  • It is one-dimensional: np.interp() is designed for 1D interpolation. For multidimensional interpolation, consider tools from scipy.interpolate.
  • It assumes straight lines: If your data follows a curve, linear interpolation may still be useful, but it may not capture the true shape.
  • It estimates, not measures: Interpolated values are approximations. They should not be treated as actual observations.

If your data is noisy, interpolation can connect noise as if it were meaningful. In that case, smoothing or filtering may be needed before interpolation.

Plotting an Interpolation Example

Here is a complete example that compares original data points with interpolated values:

import numpy as np
import matplotlib.pyplot as plt

x_known = np.array([0, 2, 5, 8, 10])
y_known = np.array([0, 4, 3, 7, 10])

x_new = np.linspace(0, 10, 50)
y_new = np.interp(x_new, x_known, y_known)

plt.scatter(x_known, y_known, label="Known points", color="red")
plt.plot(x_new, y_new, label="Interpolated line")
plt.legend()
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Linear Interpolation with np.interp")
plt.show()

This creates a chart where the red dots are original observations and the line shows interpolated values. Notice that the line changes direction only at known data points because interpolation connects each neighboring pair with a straight segment.

When Should You Use np.interp()?

Use np.interp() when you need a fast, simple, and reliable way to estimate values between known points. It is especially appropriate when your x-values are sorted, your data is one-dimensional, and a straight-line assumption is reasonable.

However, if your data has strong curvature, seasonal patterns, or complex relationships, you may want more advanced methods such as spline interpolation, polynomial fitting, or model-based forecasting. The strength of np.interp() is not sophistication; it is clarity, speed, and convenience.

Final Thoughts

NumPy np.interp() is a small function with a wide range of uses. It helps bridge gaps in data, convert measurements to new intervals, and create smoother visualizations with very little code. Once you understand that it simply draws straight lines between known points, it becomes easy to apply confidently. For many everyday Python data tasks, np.interp() is exactly the right tool: simple enough to understand immediately, yet powerful enough to solve real problems.