Reputation: 165
I'm struggling to produce an interpolation function for some 2-dimensional data I have. My data isn't standard as each value in the x-array corresponds to a unique y-array. For example:
x = [0.1, 0.2]
y1 = [13.719, 10.488, 9.885, 9.704] #Corresponding to x=0.1
y2 = [13.34, 10.259, 9.275, 8.724] #Corresponding to x=0.2
z1 = [1395., 2209., 2411., 2555.] #Corresponding to y1
z2 = [1570., 2261., 2519., 2682.] #Corresponding to y2
Ideally I would like to generate a function, f(x, y) that will return an interpolated value of z.
So far my only attempts have been through using:
from scipy.interpolate import interp2d
interpolation = interp2d(x, [y1, y2], [z1, z2])
Which, not unsurprisingly, results in the following error message:
ValueError: x and y must have equal lengths for non rectangular grid
I understand why I'm getting this message and appreciate that interp2d is not the function I should be using, but I'm unsure where to go from here.
Upvotes: 1
Views: 742
Reputation: 3460
The problem is that interp2d
works with data arranged on a rectangular grid. You only have 8 data points that are not arranged in a rectangular xy
grid.
You can consider a rectangle 2x8
that consists of all possible combinations of your x
and y
data, but you only have 8 data points (z
values).
Below is an example solution with more generic scipy.interpolate.griddata
function:
x = [0.1, 0.2]
y1 = [13.719, 10.488, 9.885, 9.704] #Corresponding to x=0.1
y2 = [13.34, 10.259, 9.275, 8.724] #Corresponding to x=0.2
z1 = [1395., 2209., 2411., 2555.] #Corresponding to y1
z2 = [1570., 2261., 2519., 2682.] #Corresponding to y2
y=np.concatenate((y1,y2)) # collapse all y-data into a single array
# obtain x- and y- grids
grid_x, grid_y =np.meshgrid(np.array(x), y)[0].T, np.meshgrid(np.array(x), y)[1].T
points=np.stack((np.repeat(x,4).T,y)) #obtain xy corrdinates for data points
values=np.concatenate((z1,z2)) #obtain values
grid_z0 = griddata(points.T, values, (grid_x, grid_y), method='nearest') #Nearest neighbour interpolation
You can generalize this code for other interpolation options / denser grids and so on.
Upvotes: 1