title: How to interpolate/extrapolate within partly empty regular grid?
body: <p>I would like to create a python function to linearly interpolate within a partly empty grid and get a nearest extrapolation out of bounds.</p>
  
  <p>Let's say I have the following data stored in pandas DataFrame:</p>
  
  <pre><code>In [1]: import numpy as np
  In [2]: import pandas as pd
  
  In [3]: x = [0,1,2,3,4]
  In [4]: y = [0.5,1.5,2.5,3.5,4.5,5.5]
  In [5]: z = np.array([[np.nan,np.nan,1.5,2.0,5.5,3.5],[np.nan,1.0,4.0,2.5,4.5,3.0],[2.0,0.5,6.0,1.5,3.5,np.nan],[np.nan,1.5,4.0,2.0,np.nan,np.nan],[np.nan,np.nan,2.0,np.nan,np.nan,np.nan]])
  In [6]: df = pd.DataFrame(z,index=x,columns=y)
  In [7]: df
  Out[7]:
      0.5  1.5  2.5  3.5  4.5  5.5
   0  NaN  NaN  1.5  2.0  5.5  3.5
   1  NaN  1.0  4.0  2.5  4.5  3.0
   2  2.0  0.5  6.0  1.5  3.5  NaN
   3  NaN  1.5  4.0  2.0  NaN  NaN
   4  NaN  NaN  2.0  NaN  NaN  NaN 
  </code></pre>
  
  <p>I would like to get function <code>myInterp</code> that returns a linear interpolation within data boundaries (i.e. not NaN values) and get a nearest extrapolation outside bounds (i.e. NaN or no values) such as:</p>
  
  <pre><code>In [1]: myInterp([1.5,2.5]) #linear interpolation
  Out[1]: 5.0
  
  In [2]: myInterp([1.5,4.0]) #bi-linear interpolation
  Out[2]: 3.0
  
  In [3]: myInterp([0.0,2.0]) #nearest extrapolation (inside grid)
  Out[3]: 1.5
  
  In [4]: myInterp([5.0,2.5]) #nearest extrapolation (outside grid)
  Out[4]: 2.0
  </code></pre>
  
  <p>I tried many combination of <code>scipy.interpolate</code> package with no success, does anyone have a suggestion how to do it ? </p>