Numpy interp – One-dimensional linear interpolation for monotonically increasing sample points

NumPy interp estimates a value between known samples by joining neighboring points with straight line segments. Give it the x-coordinate you need, the sorted sample positions, and the matching sample values.

Use numpy.interp for a value between samples

The function returns the first or last sample value when your query falls outside the sample range unless you provide left or right replacements. The sample positions in xp must increase, and xp and fp must have the same length.

import numpy as np

xp = [0, 10, 20]
fp = [0, 100, 80]
value = np.interp(15, xp, fp)
print(value)

The output is 90.0. The query 15 lies halfway between 10 and 20, so NumPy moves halfway from 100 to 80.

90.0

Interpolate several queries at once

Pass an array of query positions when you need a batch of estimates. NumPy applies the same neighboring-segment rule to each value and returns an array with the matching shape.

queries = [0, 5, 15, 25]
print(np.interp(queries, xp, fp))
[  0.  50.  90.  80.]

Choose boundary values explicitly

Outside the sample range, the defaults are fp[0] on the left and fp[-1] on the right. Set left and right when those defaults would hide a missing-data condition.

print(np.interp([-5, 25], xp, fp, left=np.nan, right=np.nan))
[nan nan]

Common input errors

  • xp and fp must contain the same number of values.
  • Use one-dimensional sequences for xp and fp.
  • A period of zero raises ValueError when periodic interpolation is requested.
  • Keep xp increasing. Duplicate sample positions can produce unexpected results.

Reference

NumPy interp documentation

Shrushti Asutkar
Shrushti Asutkar
Articles: 16