Interval Average 1D Data

I have two 1D arrays, one for measured data and one for location. For example, the measured data may be temperature, and the other may be the height of measurement:

temp = np.asarray([10, 9.6, 9.3, ..., -20.3, -21.0]) # Temperature in celsius height = np.asarray([129, 145, 167, ..., 5043, 5112]) # Height in meters 

As you can see, the measurement height is not at a regular distance.

I want to calculate the average temperature at regular intervals with intervals. This is some moving average, but the window size is variable, because the data points inside the interval of interest are not always the same.

This can be done using the for loop as follows:

 regular_heights = np.arange(0, 6000, 100) # Regular heights every 100m regular_temps = [] for i in range(len(regular_heights)-1): mask = np.logical_and(height > regular_heights[i], height < regular_heights[i+1]) mean = np.mean(temp[mask]) regular_temps.append(mean) regular_temps = np.hstack((regular_temps)) 

I really dislike this approach, and I was wondering if there would be a more “numeric” solution.

+6
source share
1 answer

You may be looking for UnivariateSpline . For instance:

 from scipy.interpolate import UnivariateSpline temp = np.asarray([10, 9.6, 9.3, 9.0, 8.7]) # Temperature in celsius height = np.asarray([129, 145, 167, 190, 213]) # Height in meters f = UnivariateSpline(height, temp) 

Now you can evaluate f wherever you want:

 regular_heights = np.arange(120, 213, 5) # Regular heights every 5m plot(height, temp, 'o', regular_heights, f(regular_heights), 'x') 

enter image description here

+3
source

Source: https://habr.com/ru/post/945769/


All Articles