Search code examples
pythonnumpyinterpolation

Numpy calculate values in middle


I have numpy array which represents my x-axis, ex.

x = [1, 2, 3, 4, 5]

I want to get values in the middle of two adjacent element, so my example array should turn into

x_interp = [1.5, 2.5, 3.5, 4.5]

Is there a fast and convinient way to do this using python/numpy


Solution

  • If you have a numpy array, just slice with a shift:

    x = np.array([1, 2, 3, 4, 5])
    
    x_interp = (x[1:]+x[:-1])/2
    

    Output: array([1.5, 2.5, 3.5, 4.5])

    An alternative (and also more generic approach to get the mean of every N items) would be to use sliding_window_view:

    from numpy.lib.stride_tricks import sliding_window_view as swv
    
    N = 2
    x_interp = swv(x, N).mean(axis=1)