2

I'm using NumPy's linspace to fill in data between points.

lats = (-66.44421,-66.57947,-64.81464,-64.69528)
lons = (-73.03290,-72.73904,-64.71657,-65.03036)
NO3  = (33.48,24.01,17.20,20.03) 

xi = np.linspace(min(lats),max(lats),360)
yi = np.linspace(min(lons),max(lons),360)

# grid the data.
zi = griddata((lats, lons), NO3, (xi[None,:], yi[:,None]), method='cubic')
# contour the gridded data.
plt.contourf(xi,yi,zi,15,cmap=cMap)
plt.colorbar()
# plot data points.
plt.scatter(lats,lons,facecolors='none', edgecolors='k',s=26)
plt.show()

I want to retrieve values (missing samples) from the gridded data zi based on coordinate pairs generated from linspace, but the coordinates aren't exact for a dict lookup:

# record index and value of linspace coordinates as key and value
xi_coords = {value: index for index, value in enumerate(xi)}
yi_coords = {value: index for index, value in enumerate(yi)}
# how to retrieve a value inbetween at say... (-65.11018,-67.08512)
zi[xi_coords[-65.11018], yi_coords[-67.08512]]

Returns a Key error. Is there a smarter workaround for this problem?

martineau
  • 119,623
  • 25
  • 170
  • 301
leon yin
  • 829
  • 3
  • 10
  • 23

2 Answers2

1

If I'm not mistaken the point you try to retrieve is not in your linspace, it is not just a numerical precision problem... If you want to find the closest grid point to any given point, you should define functions rather than using dicts:

latmin = min(lats)
latmax = max(lats)
npoints = 360

def get_lat_index(lat):
    return int(round((npoints-1)*(lat-latmin)/(latmax-latmin)))

and similar for longitudes.

Julien
  • 13,986
  • 5
  • 29
  • 53
0

One option is rounding. For example to two decimals:

xi_coords = {round(value, 2): index for index, value in enumerate(xi)}
yi_coords = {round(value, 2): index for index, value in enumerate(yi)}
zi[xi_coords[-65.11], yi_coords[-67.08]]
Mike Müller
  • 82,630
  • 20
  • 166
  • 161