1

This has been kicking my butt for a bit....

I have the following information:

 1. a 1-D array of longitudes
 2. a 1-D array of latitudues
 3. a 2-D array of some quantity (sized len(lat),len(long))

What I want to do is get a subset of the array based on a range of latitudes and longitudes

I've tried something like this

ii = find( (lon >= xlims[0]) & (lon <= xlims[1]) )
jj = find( (lat >= ylims[0]) & (lat <= ylims[1]) )
z=array[jj, ii]

ValueError: shape mismatch: objects cannot be broadcast to a single shape

I have tried this using a boolean approach

ii = ( (lon >= xlims[0]) & (lon <= xlims[1]) )
jj = ( (lat >= ylims[0]) & (lat <= ylims[1]) )

but get the same error.

There is probably something subtle here I am missing... any thoughts?

1 Answer 1

2

I don't know what your find function does, but you can use np.ix_. First let's make some dummy data:

>>> lon = np.arange(10)
>>> lat = np.linspace(40,50,17)
>>> quant = np.random.random((len(lon),len(lat)))
>>> ii = (lon >= 2) & (lon < 5)
>>> jj = (lat >= 42) & (lat <= 44)

which gives me (for this data)

>>> ii
array([False, False,  True,  True,  True, False, False, False, False, False], dtype=bool)
>>> jj
array([False, False, False, False,  True,  True,  True, False, False,
       False, False, False, False, False, False, False, False], dtype=bool)

When we feed this into np.ix_, we get something we can use to index:

>>> np.ix_(ii,jj)
(array([[2],
       [3],
       [4]]), array([[4, 5, 6]]))

and so

>>> quant[np.ix_(ii,jj)]
array([[ 0.51567424,  0.84138194,  0.6267137 ],
       [ 0.1865154 ,  0.7785198 ,  0.16720573],
       [ 0.80563691,  0.82990892,  0.28402503]])
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks... this is good stuff. The "find" is part of the numpy package and is similar to the Matlab find.... it returns the indices where the selected constraint is true. This is one of those times where the transition from Matlab to Python is not straight forward. So following your example to a larger array.... >>>>lon = np.arange(10) >>> lat = np.linspace(40,50,17) >>> quant = np.random.random((len(lon),len(lat)))
Do you mean np.where?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.