find indices of lat lon point on a grid using python
<p>I am new to python, and I can't figure out how to find the minimum distance from a given lat/lon point (which is not given from the grid, but selected by me) to a find the closest indices of a lat/lon point on a grid.</p>

<p>Basically , I am reading in an ncfile that contains 2D coordinates:</p>

<pre><code>coords = 'coords.nc'
fh = Dataset(coords,mode='r')
lons = fh.variables['latitudes'][:,:]
lats = fh.variables['longitudes'][:,:]
fh.close()

&gt;&gt;&gt; lons.shape
(94, 83)
&gt;&gt;&gt; lats.shape
(94, 83)
</code></pre>

<p>I want to find the indices in the above grid for the nearest lat lon to the below values:    </p>

<pre><code>sel_lat=71.60556
sel_lon=-161.458611
</code></pre>

<p>I tried to make lat/lon pairs in order to use the scipy.spatial.distance function, but I still am having problems because I did not set up the input arrays to the format it wants, but I don't understand how to do that:</p>

<pre><code>latLon_pairsGrid = np.vstack(([lats.T],[lons.T])).T

&gt;&gt;&gt; latLon_pairsGrid.shape
(94, 83, 2)

distance.cdist([sel_lat,sel_lon],latLon_pairsGrid,'euclidean')
</code></pre>

<p>Any help or hints would be appreciated</p>

<p>I think I found an answer, but it is a workaround that avoids calculating distance between the chosen lat/lon and the lat/lons on the grid.  This doesn't seem completely accurate because I am never calculating distances, just the closest difference between lat/lon values themselves.</p>

<p>I used the answer to the question <a href="http://stackoverflow.com/questions/28006077/find-i-j-location-of-closest-long-lat-values-in-a-2d-array">find (i,j) location of closest (long,lat) values in a 2D array</a></p>

<pre><code>a = abs(lats-sel_lat)+abs(lons-sel_lon)
i,j = np.unravel_index(a.argmin(),a.shape)
</code></pre>

<p>Using those returned indices i,j, I can then find on the grid the coordinates that correspond most closely to my selected lat, lon value:</p>

<pre><code>&gt;&gt;&gt; lats[i,j]
71.490295
&gt;&gt;&gt; lons[i,j]
-161.65045
</code></pre>

python coordinates netcdf