[Numpy-discussion] Newby question: best way to create a list of indices
Scott Sinclair
scott.sinclair.za at gmail.com
Wed Jun 9 09:55:18 EDT 2010
>On 9 June 2010 12:01, Hanlie Pretorius <hanlie.pretorius at gmail.com> wrote:
> I'm reading netCDF files using pupynere and I want to extract 22
> values from a 1440x400 array. I have the indices of the values, they
> are:
>
> 92 832
> 92 833
> 91 832
> 91 833
...
>
> What is the best way to store these indices so that I can
> programmatically extract the values? I have tried storing them in
> pairs
> -----
> (index1='92,832')
> -----
> and then I can use:
> -----
> precipitation.data[int(index1[:2]),int(index1[3:])]
> -----
> Is there a better way? The values are also not regular enough to use a
> nested loop, as far as I can see.
This is a use case where NumPy is very convenient. You can use fancy indexing
>>> import numpy as np
>>> a = np.random.random((1440, 400))
>>> rows = [832, 833, 832, 833] # first 4 rows
>>> cols = [92, 92, 91, 91] # first 4 cols
>>> a[rows, cols]
array([ 0.56539344, 0.14711586, 0.40491459, 0.29997256])
>>> a[832, 92] # check
0.56539343852732926
Read more here http://docs.scipy.org/doc/numpy/user/basics.indexing.html#index-arrays
Cheers,
Scott
More information about the NumPy-Discussion
mailing list