[SciPy-User] Replace duplicates in a monotonically increasing array with linearly interpolated values.

Vincent Schut schut@sarvision...
Mon Sep 13 03:57:09 CDT 2010


On 09/10/2010 08:26 PM, Dharhas Pothina wrote:
> Hi,
>
> I have an monotonically increasing array with duplicates in it. e.g.
>
> x = np.array([1.0,1.0,1.0,2.0,2.0,3.0,3.0,3.0,4.0,4.0,5.0,5.0,5.0,5.0,6.0])
>
> I need a new array of the same size with linearly interpolated values i.e something like
>
> np.array([1.0, 1.33, 1.67, 2.0, 2.5, 3.0, 3.33, 3.67, 4.0, 4.5, 5.0, 5.25, 5.5, 5.75, 6.0])
>
> Is there an efficient way to do this. Right now I'm looping through the array and maintaining position flags of when the value changes and then doing linear interpolation between the start and end flags before resetting the flags moving to the next section. This is pretty slow.
>
> I realize there will be a problem on how to deal with duplicates at the end of the array.
>
> thanks
>
> - dharhas

Hmm, something like this should do the trick (not tested):

xUnique, xUniqueIndices = scipy.unique(x, return_index=True)
# get piecewise linear interpolation
xInterpolated = numpy.interp(numpy.arange(len(x), xUniqueIndices, xUnique)

note: this will not interpolate duplicates at the beginning/end. You can 
however adjust the behaviour for those, see the docs for numpy.interp.


Vincent.


More information about the SciPy-User mailing list