Home > Back-end >  NumPy: how to "scale" an array "smoothly"
NumPy: how to "scale" an array "smoothly"

Time:01-23

Say I have a numpy array like this

array([1, 3, 5, 7, 9, 11])

And I would like to "scale" it by a factor of two, filling in the "gaps" using the mean of two adjacent numbers. Result:

array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 11])

Anyone knows how to do this?

CodePudding user response:

Here is a simple function you can use.

def double_list(arr):
    new_arr = []
    for i in range(len(arr)):
        new_arr.append(arr[i])
        if i == 0 or i == len(arr) - 1:
            new_arr.append(arr[i])
        else:
            new_arr.append(int((arr[i]   arr[i   1]) / 2))
    return new_arr


print(double_list(arr))

CodePudding user response:

Using numpy arange function

arr = np.array([1, 3, 5, 7, 9, 11])

arr2 = np.arange(arr.min(),arr.max()   1)
print(arr2)

Output:

[ 1  2  3  4  5  6  7  8  9 10 11]

To get the output as per your requirement

arr2 = np.append(np.arange(arr.min(),arr.max()   1), arr.max())
print(arr2)

Output:

[ 1  2  3  4  5  6  7  8  9 10 11 11]
  •  Tags:  
  • Related