【问题标题】:Indexing Multi-dimensional arrays索引多维数组
【发布时间】:2015-11-04 21:54:51
【问题描述】:

我知道多维 numpy 数组可能会被其他数组索引,但我没有弄清楚以下是如何工作的:

我想要 raster 中的项目,一个 3d numpy 数组,基于 indx,一个 3d 索引数组:

raster=np.random.rand(5,10,50)
indx=np.random.randint(0, high=50, size=(5,10,3))

我想要的是另一个维度为indx 的数组,它根据indx 的索引保存raster 的值。

【问题讨论】:

  • 您可以将预期的输出添加到您的问题中吗?并解释一下你获得该输出的逻辑是什么?

标签: python arrays numpy multidimensional-array indexing


【解决方案1】:

为了在广播期间正确解析您的索引,我们需要两个数组 ab 以便 raster[a[i,j,k],b[i,j,k],indx[i,j,k]] 将是 raster[i,j,indx[i,j,k]] 对应范围内的 i,j,k对于indx 的轴。 最简单的解决方案是:

x,y,z = indx.shape
a,b,_ = np.ogrid[:x,:y,:z]
raster[a,b,indx]

其中np.ogrid[...] 创建了三个形状为(x,1,1)(1,y,1)(1,1,z) 的数组。我们不需要最后一个,所以我们把它扔掉。现在,当其他两个使用 indx 广播时,它们的行为完全符合我们的需要。

【讨论】:

    【解决方案2】:

    如果我正确理解了这个问题,对于indx 的每一行,您都在尝试索引raster 中的相应行,但列号取决于indx 中的实际值。因此,有了这个假设,您可以使用使用线性索引的矢量化方法,就像这样 -

    M,N,R = raster.shape
    linear_indx = R*np.arange(M*N)[:,None] + indx.reshape(M*N,-1)
    out = raster.ravel()[linear_indx].reshape(indx.shape)
    

    【讨论】:

      【解决方案3】:

      我假设您想从每个 3 维数组中获取 3 个随机值。

      感谢advanced indexing,您可以通过列表理解来做到这一点

      这是一个使用较少数量的值和整数的示例,因此输出更易于阅读:

      import numpy as np
      
      raster=np.random.randint(0, high=1000, size=(2,3,10))
      indices=np.random.randint(0, high=10, size=(2,3,3))
      results = np.array([ np.array([ column[col_indices] for (column, col_indices) in zip(row, row_indices) ]) for (row, row_indices) in zip(raster, indices) ])
      
      print("Raster:")
      print(raster)
      print("Indices:")
      print(indices)
      print("Results:")
      print(results)
      

      输出:

      Raster:
      [[[864 353  11  69 973 475 962 181 246 385]
        [ 54 735 871 218 143 651 159 259 785 383]
        [532 476 113 888 554 587 786 172 798 232]]
      
       [[891 263  24 310 652 955 305 470 665 893]
        [260 649 466 712 229 474   1 382 269 502]
        [323 513  16 236 594 347 129  94 256 478]]]
      Indices:
      [[[0 1 2]
        [7 5 1]
        [7 8 9]]
      
       [[4 0 2]
        [6 1 4]
        [3 9 2]]]
      Results:
      [[[864 353  11]
        [259 651 735]
        [172 798 232]]
      
       [[652 891  24]
        [  1 649 229]
        [236 478  16]]]
      

      它同时迭代 rasterindices 中相应的 3 维数组,并使用高级索引从 raster 中分割所需的索引。

      这是一个更详细的版本,它做同样的事情:

      results = []
      for i in range(len(raster)):
          row = raster[i]
          row_indices = indices[i]
          row_results = []
          for j in range(len(row)):
              column = row[j]
              column_indices = row_indices[j]
              column_results = column[column_indices]
              row_results.append(column_results)
          results.append(np.array(row_results))
      results = np.array(results)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-07-17
        • 1970-01-01
        • 2016-07-16
        • 2015-04-19
        相关资源
        最近更新 更多