【问题标题】:Python + 2-D array slicing + valueerror: operands could not be broadcast togetherPython + 2-D 数组切片 + valueerror:操作数不能一起广播
【发布时间】:2015-01-14 18:39:17
【问题描述】:

这已经让我有点头疼了....

我有以下信息:

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

但得到同样的错误。

我可能在这里遗漏了一些微妙的东西......有什么想法吗?

【问题讨论】:

    标签: python arrays slice


    【解决方案1】:

    我不知道你的find 函数是做什么的,但你可以使用np.ix_。首先让我们做一些虚拟数据:

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

    【讨论】:

    • 谢谢...这是好东西。 “查找”是 numpy 包的一部分,类似于 Matlab 查找...。它返回所选约束为真的索引。这是从 Matlab 到 Python 的过渡并不直接的时期之一。所以按照你的例子到一个更大的数组.... >>>>lon = np.arange(10) >>> lat = np.linspace(40,50,17) >>> quant = np.random.random( (len(lon),len(lat)))
    • 你的意思是np.where
    猜你喜欢
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    • 1970-01-01
    • 2012-10-31
    相关资源
    最近更新 更多