问题
I have a number of height values across a grid, specified in a series of lists:
[3, 1, -2, -3, -3] # x = 0m
[2, -7, -14, -30, -39] # x = 10m
[46, 22, 5, -2, -8] # x = 20m
The example above shows a 40m x 20m grid in the form
[x=0y=0, x=0y=10...][x=10y=0, x=10y=10...] etc.
I need to calculate the height at a specific x,y coordinate. I have looked at various interpolate functions and example but can't make any sense out of them - please help!
An example would be the height at x = 5m, y = 5m in teh grid above, which would be in the middle of the values 3, 1 2 and -7 (-1ish?)
Thanks
回答1:
You can use scipy.interpolate.interp2d. The code below should do the job:
import numpy as np
from scipy.interpolate import interp2d
# Original data (e.g. measurements)
a = [3, 1, -2, -3, -3]
b = [2, -7, -14, -30, -39]
c = [46, 22, 5, -2, -8]
x = [0, 10, 20] # x-coordinates
y = [0, 10, 20, 30, 40] # y-coordinates
# Organise data in matrix
z = np.vstack([a, b, c]).T
# Create interpolation function
f_z = interp2d(x, y, z)
# Desired x/y values
x_interp = 5
y_interp = 5
# Collect interpolated z-value
z_interp = f_z(x_interp, y_interp)
print(z_interp) # (result: [-0.25])
回答2:
Solution: Transform into 2D array
import numpy as np
a = [3, 1, -2, -3, -3] # x = 0m
b = [2, -7, -14, -30, -39] # x = 10m
c = [46, 22, 5, -2, -8] # x = 20m
all_lists = [a,b,c]
grid = np.vstack(all_lists) # Edit: thanks @jochen for better code
>>print(grid.shape)
(3, 5)
Now you can access grid via x,y coordinates
grid[1,1]
and etc
Based on this, you can create logic.
If x = 5, y = 5, then you can create square corners indexes by this:
indexes: x/5 +0, x/5+1, y/5,y/5+1 ---> by combining them you get [0,0],[0,1],[1,0],[1,1]
At the end you just feed grid with those indexes
SUM = grid[0,0] + grid[0,1] + grid[1,0] + grid[1,1]
回答3:
You can achieve this with interpolate.gridddata function from scipy.
With below code you can get the any interpolation you want from your grid.
import itertools
import numpy as np
from scipy.interpolate import griddata
dataX0 = [3, 1, -2, -3, -3] # x = 0m
dataX10 = [2, -7, -14, -30, -39] # x = 10m
dataX20 = [46, 22, 5, -2, -8] # x = 20m
data = dataX0 + dataX10 + dataX20
points = list(itertools.product(range(0,30,10),range(0,50,10)))
outputPoint = (5,5)
outputValue = griddata(points=points,values=data, xi=outputPoint, method="cubic")
print outputValue
The example above give you the interpolation at ouputPoint
(5,5)
. And the output would give:
>>>
-2.78976054957
来源:https://stackoverflow.com/questions/54022277/interpolating-within-a-grid-in-python