[英]keeping track of indices change in numpy.reshape
While using numpy.reshape
in Python, is there a way to keep track of the change in indices? 在Python中使用numpy.reshape
时,有没有办法跟踪索引的变化?
For example, if a numpy array with the shape (m,n,l,k)
is reshaped into an array with the shape (m*n,k*l)
; 例如,如果将具有形状(m,n,l,k)
的numpy数组重新整形为具有形状(m*n,k*l)
的数组; is there a way to get the initial index ( [x,y,w,z]
) for the current [X,Y]
index and vice versa? 有没有办法获得当前[X,Y]
索引的初始索引( [x,y,w,z]
),反之亦然?
Yes there is, it's called raveling
and unraveling
the index. 是的,它被称为raveling
并unraveling
索引。 For example you have two arrays: 例如,您有两个数组:
import numpy as np
arr1 = np.arange(10000).reshape(20, 10, 50)
arr2 = arr.reshape(20, 500)
say you want to index the (10, 52)
(equivalent to arr2[10, 52]
) element but in arr1
: 假设您要索引(10, 52)
arr2[10, 52]
(10, 52)
(相当于arr2[10, 52]
)元素,但在arr1
:
>>> np.unravel_index(np.ravel_multi_index((10, 52), arr2.shape), arr1.shape)
(10, 1, 2)
or in the other direction: 或在另一个方向:
>>> np.unravel_index(np.ravel_multi_index((10, 1, 2), arr1.shape), arr2.shape)
(10, 52)
You don't keep track of it, but you can calculate it. 你没有跟踪它,但你可以计算它。 The original mxn
is mapped onto the new m*n
dimension, eg n*x+y == X
. 原始mxn
映射到新的m*n
维度,例如n*x+y == X
But we can verify with a couple of multidimensional ravel/unravel functions (as answered by @MSeifert
). 但我们可以使用几个多维ravel / @MSeifert
函数进行验证(由@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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.