【问题标题】:Python: Access saved points from 2d array in 3d numpy arrayPython:从 3d numpy 数组中的 2d 数组访问保存的点
【发布时间】:2019-03-09 15:40:09
【问题描述】:

我得到了一个 2d numpy 数组 (shape(y,x)=601,1200) 和一个 3d numpy 数组 (shape(z,y,x)=137,601,1200)

在我的 2d 数组中,我将 z 值保存在 y, x 点,我现在想从我的 3d 数组中访问它并将其保存到新的 2d 数组中。

我尝试了类似的方法但没有成功。

levels = array2d.reshape(-1)
y = np.arange(601)
x = np.arange(1200)
newArray2d=oldArray3d[levels,y,x]

IndexError: 形状不匹配:索引数组无法与形状 (721200,) (601,) (​​1200,) 一起广播

我不想尝试使用循环,那么有更快的方法吗?

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    这是您拥有的数据:

    x_len = 12     # In your case, 1200
    y_len = 6      # In your case, 601
    z_len = 3      # In your case, 137
    
    import numpy as np
    my2d = np.random.randint(0,z_len,(y_len,x_len))
    my3d = np.random.randint(0,5,(z_len,y_len,x_len))
    

    这是构建新二维数组的一种方法:

    yindices,xindices = np.indices(my2d.shape)
    new2d = my3d[my2d[:], yindices, xindices]
    

    注意事项:

    1. 我们正在使用整数高级索引。
    2. 这意味着我们使用 3 个整数索引数组来索引 3d 数组 my3d
    3. 有关整数数组索引如何工作的更多说明,请参阅my answer on this other question
    4. 在您的尝试中,没有必要使用 reshape(-1) 重塑您的 2d,因为我们传递的整数索引数组的形状(在任何广播之后)将成为生成的 2d 数组的形状。
    5. 此外,在您的尝试中,您的第二个和第三个索引数组需要具有相反的方向。也就是说,它们的形状必须为 (y_len,1)(1, x_len)。注意1 的不同位置。这确保了这两个索引数组将被广播

    【讨论】:

    • 快速简单。谢谢@fountainhead!
    【解决方案2】:

    您的问题有些含糊,但我认为您希望像这样进行高级索引:

    In [2]: arr = np.arange(24).reshape(4,3,2)                                      
    In [3]: levels = np.random.randint(0,4,(3,2))                                   
    In [4]: levels                                                                  
    Out[4]: 
    array([[1, 2],
           [3, 1],
           [0, 2]])
    In [5]: arr                                                                     
    Out[5]: 
    array([[[ 0,  1],
            [ 2,  3],
            [ 4,  5]],
    
           [[ 6,  7],
            [ 8,  9],
            [10, 11]],
    
           [[12, 13],
            [14, 15],
            [16, 17]],
    
           [[18, 19],
            [20, 21],
            [22, 23]]])
    In [6]: arr[levels, np.arange(3)[:,None], np.arange(2)]                         
    Out[6]: 
    array([[ 6, 13],
           [20,  9],
           [ 4, 17]])
    

    levels 是 (3,2)。我创建了另外 2 个索引数组,它们用它 (3,1) 和 (2,) 进行广播。结果是来自 arr 的 (3,2) 数组值,由它们的组合索引选择。

    【讨论】:

    • 我选择了喷泉的解决方案。但也谢谢你! @hpaulj
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-27
    • 2016-04-07
    • 2012-12-09
    • 1970-01-01
    • 1970-01-01
    • 2020-10-03
    相关资源
    最近更新 更多