Home > OS >  Increase (or decrease) spacing between values in a numpy array
Increase (or decrease) spacing between values in a numpy array

Time:01-24

I would like to transform an array so that the "spacing" between values are increased (or decreased) by a specific amount. For example, say that I've got arr and want to increase the spacing (difference) in between each value in new_arr by 0.1:

arr = [10.0, 6.5, 3.0, 1.3]

new_arr = [10.15, 6.55, 2.95, 1.15]

In reality, my array is much longer, containing surface elevations that I would like to compress or expand by performing some sort of transformation.

Does anyone have a suggestion?

Cheers.

CodePudding user response:

Does this do what you require?

import numpy as np

delta = 0.1
arr = np.array( [10., 6.5, 3, 1.3 ])

diff = np.diff( arr, prepend = 0. )
diff
# array([10. , -3.5, -3.5, -1.7])

diff[ 1:]  = np.sign( diff[1:] ) * delta  # Add or subtract the delta
diff
# array([10. , -3.6, -3.6, -1.8])

new_arr = diff.cumsum()
new_arr
# array([10. ,  6.4,  2.8,  1. ])

new_arr  = arr.mean() - new_arr.mean() 
# Make the mean of new_array the same as that of arr

new_arr
# array([10.15,  6.55,  2.95,  1.15])

This can be wrapped up in a function:

def expand_diff( arr, delta ):
    diff = np.diff( arr, prepend = 0.0 )
    diff[1:]  = np.sign( diff[1:] ) * delta
    new_arr = diff.cumsum()
    return new_arr   arr.mean() - new_arr.mean()

arr = np.array( [10., 6.5, 3, 1.3 ])
expand_diff( arr, .1 )
# array([10.15,  6.55,  2.95,  1.15])

# Without consistent decreasing/increasing
expand_diff( np.array( [ 10.5, 6., 9., 4., 3.1 ] ), .1 )
# array([10.58,  5.98,  9.08,  3.98,  2.98])

np.diff( np.array( [ 10.5, 6., 9., 4., 3.1 ] ) )
# array([-4.5,  3. , -5. , -0.9])

np.diff(expand_diff( np.array( [ 10.5, 6., 9., 4., 3.1 ] ), .1 ))
# array([-4.6,  3.1, -5.1, -1. ])

CodePudding user response:

You could do

import numpy as np

arr = np.array([10.0,6.5,3.0,1.3])
stretch = 0.1

d = np.arange(-len(arr),0,-1) * stretch
d = d - np.mean(d)

arr  = d

# arr = np.array([10.15,6.55,2.95,1.15])
  •  Tags:  
  • Related