简体   繁体   中英

Python + 2-D array slicing + valueerror: operands could not be broadcast together

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?

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]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM