Python+2D数组切片+valueerror:操作数无法广播到一起

2024-04-26 20:49:42 发布

您现在位置:Python中文网/ 问答频道 /正文

这件事已经折磨了我一段时间了。。。。你知道吗

我有以下信息:

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

我要做的是根据纬度和经度范围得到数组的子集

我试过这样的方法

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

但得到同样的错误。你知道吗

我可能错过了一些微妙的东西。。。有什么想法吗?你知道吗


Tags: of信息lensomefindarrayiilon
1条回答
网友
1楼 · 发布于 2024-04-26 20:49:42

我不知道你的find函数做什么,但是你可以使用^{}。首先让我们制作一些虚拟数据:

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

这给了我(这个数据)

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

当我们把它输入np.ix_时,我们得到了一些可以用来索引的东西:

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

所以呢

>>> quant[np.ix_(ii,jj)]
array([[ 0.51567424,  0.84138194,  0.6267137 ],
       [ 0.1865154 ,  0.7785198 ,  0.16720573],
       [ 0.80563691,  0.82990892,  0.28402503]])

相关问题 更多 >