I’m rather new to NumPy. Anyone have an idea for making this code, especially the nested loops, more compact/efficient? BTW, dist and data are three-dimensional numpy arrays.
def interpolate_to_distance(self,distance):
interpolated_data=np.ndarray(self.dist.shape[1:])
for j in range(interpolated_data.shape[1]):
for i in range(interpolated_data.shape[0]):
interpolated_data[i,j]=np.interp(
distance,self.dist[:,i,j],self.data[:,i,j])
return(interpolated_data)
Thanks!
Alright, I’ll take a swag with this:
It at least removes one loop (and those nested indices), but it’s not much faster than the original, ~20% faster according to
%timeitin IPython. On the other hand, there’s a lot of (probably unnecessary, ultimately) transposing and reshaping going on.For the record, I wrapped it up in a dummy class and filled some 3 x 3 x 3 arrays with random numbers to test:
Which prints (for my particular set of randoms):
I also tried
np.vectorize(np.interp)but couldn’t get that to work. I suspect that would be much faster if it did work.I couldn’t get
np.fromfunctionto work either, as it passed (2) 3 x 3 (in this case) arrays of indices tonp.interp, the same arrays you get fromnp.mgrid.One other note: according the the docs for
np.interp,Obviously, my random numbers violate the ‘always increasing’ rule, but you’ll have to be more careful.