EDIT: added prefix / suffix value to interval arrays to make them the same length as their corresponding data arrays, as per @user1319128 ‘s suggestion and indeed interp does the job. For sure his solution was workable and good. I just couldn’t see it because I was tired and stupid.
I am sure this is a fairly mundane application, but so I have failed to find or come up with a way to do this without doing it outside of numpy. Maybe my brain just needs a rest, anyway here is the problem with example and solution requirements.
So I have to arrays with different lengths and I want to apply common time intervals between them to these arrays, so that that the result is I have versions of these arrays that are all the same length and their values relate to each other at the same row (if that makes sense). In the example below I have named this functionality “apply_timeintervals_to_array”. The example code:
import numpy as np from colorsys import hsv_to_rgb num_xy = 20 num_colors = 12 #xy = np.random.rand(num_xy, 2) * 1080 xy = np.array([[ 687.32758344, 956.05651214], [ 226.97671414, 698.48071588], [ 648.59878864, 175.4882185 ], [ 859.56600997, 487.25205922], [ 794.43015178, 16.46114312], [ 884.7166732 , 634.59100322], [ 878.94218682, 835.12886098], [ 965.47135726, 542.09202328], [ 114.61867445, 601.74092126], [ 134.02663822, 334.27221884], [ 940.6589034 , 245.43354493], [ 285.87902276, 550.32600784], [ 785.00104142, 993.19960822], [1040.49576307, 486.24009511], [ 165.59409198, 156.79786175], [1043.54280058, 313.09073855], [ 645.62878826, 100.81909068], [ 625.78003257, 252.17917611], [1056.77009875, 793.02218098], [ 2.93152052, 596.9795026 ]]) xy_deltas = np.sum((xy[1:] - xy[:-1])**2, axis=-1) xy_ti = np.concatenate(([0.0], (xy_deltas) / np.sum(xy_deltas))) colors_ti = np.concatenate((np.linspace(0, 1, num_colors), [1.0])) common_ti = np.unique(np.sort(np.concatenate((xy_ti, colors_ti)))) common_colors = (np.array(tuple(hsv_to_rgb(t, 0.9, 0.9) for t in np.concatenate(([0.0], common_ti, [1.0])))) * 255).astype(int)[1:-1] common_xy = apply_timeintervals_to_array(common_ti, xy)
So one could then use the common arrays for additional computations or for rendering.
The question is what could accomplish the “apply_timeintervals_to_array” functionality, or alternatively a better way to generate the same data.
I hope this is clear enough, let me know if it isn’t. Thank you in advance.
Advertisement
Answer
I think , numpy.interp
should meet your expectations.For example, If a have an 2d array of length 20 , and would like to interpolate at different common_ti
values ,whose length is 30 , the code would be as follows.
xy = np.arange(0,400,10).reshape(20,2) xy_ti = np.arange(20)/19 common_ti = np.linspace(0,1,30) x=np.interp(common_ti,xy_ti,xy[:,0]) # interpolate the first column y=np.interp(common_ti,xy_ti,xy[:,1]) #interpolate the second column