Reputation: 1
I am trying to interpolate on a 2d array where the array has between its values zeros, which I want to replace these values with values that are close to or around these values, I have been reviewing several examples but I have not been successful in my search, I have tried the following interpolation code.
import numpy as np
from scipy import interpolate
mymin,mymax = 0,3
X = np.linspace(mymin,mymax,4)
Y = np.linspace(mymin,mymax,4)
x,y = np.meshgrid(X,Y)
test = np.array([[ 1.2514318 , 0, 1.25148472, 1.25151133],
[ 1.25087456, 0, 1.25092764, 1.25095435],
[ 1.25031581, 1.25034238, 1.25036907, 0],
[ 0, 1.24978222, 0, 1.24983587]])
f = interpolate.interp2d(x,y,test,kind='linear')
X_n = np.linspace(mymin,mymax,4)
Y_n = np.linspace(mymin,mymax,4)
test_n = f(X_n,Y_n)
print (test_n)
[[ 1.25143180e+00 2.77555756e-16 1.25148472e+00 1.25151133e+00]
[ 1.25087456e+00 2.49800181e-16 1.25092764e+00 1.25095435e+00]
[ 1.25031581e+00 1.25034238e+00 1.25036907e+00 1.38777878e-17]
[ 5.33635770e-17 1.24978222e+00 -1.11022302e-16 1.24983587e+00]]
As you can see if it works correctly but the places where the zeros were, it became a very small value that does not correspond to its values that are around it, would the way I am interpolating have a failure?
Upvotes: 0
Views: 3837
Reputation: 10792
Python can not know that you do not want to consider the zero values. So you need to remove them from your 2D array:
import numpy as np
from scipy import interpolate
# Dummy data
d = np.array([[1.2514318 , 0, 1.25148472, 1.25151133],
[1.25087456, 0, 1.25092764, 1.25095435],
[1.25031581, 1.25034238, 1.25036907, 0 ],
[0, 1.24978222, 0, 1.24983587]])
# Get the index of the non zero values
y,x = np.where(d!=0)
# Create your interpolation function on the non zero values
f = interpolate.interp2d(x,y,d[d!=0],kind='linear')
# Interpolate
X = np.arange(len(d))
print(f(X,X))
# OUTPUT:
#[[1.2514318 1.25145823 1.25148472 1.25151133]
# [1.25087456 1.25090106 1.25092764 1.25095435]
# [1.25031581 1.25034238 1.25036907 1.25039598]
# [0.94306808 1.24978222 1.39770265 1.24983587]]
Noticed that this 2D linear interpolation provide some pretty bad result for the values that are on the boundary of your space domain. This was expected since a linear interpolation cannot guess what are the values that are outside the given space domain.
Upvotes: 1