【问题标题】:keeping track of indices change in numpy.reshape跟踪 numpy.reshape 中的索引变化
【发布时间】:2017-06-10 00:41:53
【问题描述】:

在 Python 中使用 numpy.reshape 时,有没有办法跟踪索引的变化?

例如,如果一个形状为(m,n,l,k)的numpy数组被reshape成一个形状为(m*n,k*l)的数组;有没有办法获取当前[X,Y] 索引的初始索引([x,y,w,z]),反之亦然?

【问题讨论】:

    标签: python numpy multidimensional-array indexing reshape


    【解决方案1】:

    您无需跟踪它,但您可以计算它。原始的m x n 映射到新的m*n 维度,例如n*x+y == X。但我们可以通过几个多维 ravel/unravel 函数进行验证(由 @MSeifert 回答)。

    In [671]: m,n,l,k=2,3,4,5
    In [672]: np.ravel_multi_index((1,2,3,4), (m,n,l,k))
    Out[672]: 119
    In [673]: np.unravel_index(52, (m*n,l*k))
    Out[673]: (2, 12)
    

    【讨论】:

      【解决方案2】:

      是的,它被称为ravelingunraveling 索引。例如你有两个数组:

      import numpy as np
      
      arr1 = np.arange(10000).reshape(20, 10, 50)
      arr2 = arr.reshape(20, 500)
      

      假设你想索引(10, 52)(相当于arr2[10, 52])元素但在arr1

      >>> np.unravel_index(np.ravel_multi_index((10, 52), arr2.shape), arr1.shape)
      (10, 1, 2)
      

      或在另一个方向:

      >>> np.unravel_index(np.ravel_multi_index((10, 1, 2), arr1.shape), arr2.shape)
      (10, 52)
      

      【讨论】:

        猜你喜欢
        • 2016-07-26
        • 1970-01-01
        • 1970-01-01
        • 2019-12-07
        • 1970-01-01
        • 1970-01-01
        • 2020-04-02
        • 1970-01-01
        • 2021-12-12
        相关资源
        最近更新 更多