Search code examples
pythonnumpyinsert

How to insert mean of each two values between them in a numpy array


I have a numpy array and want to insert the average of each two values between them. This is my array:

import numpy as np
incomp_arr = np.array([1., 2., 3., 4., 6., 0.])

I want to add averages between each two value to have:

comp_arr = np.array([1., 1.5, 2., 2.5, 3., 3.5, 4., 5., 6., 3., 0.])

at the moment I can only make the average array from incomplete_arr using:

avg_arr = ((incomp_arr + np.roll(incomp_arr,1))/2.0)[1:]

I very much appreciate any help to do so.


Solution

  • If you change how you compute avg_arr you can do:

    avg_arr = ((incomp_arr + np.roll(incomp_arr, -1))/2.0)
    # array([1.5, 2.5, 3.5, 5. , 3. , 0.5])
    
    np.vstack([incomp_arr, avg_arr]).flatten('F')[:-1]
    # array([1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 5. , 6. , 3. , 0. ])