While using numpy.reshape
in Python, is there a way to keep track of the change in indices?
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)
; is there a way to get the initial index ([x,y,w,z]
) for the current [X,Y]
index and vice versa?
Yes there is, it's called raveling
and unraveling
the index. 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
:
>>> 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 m x n
is mapped onto the new m*n
dimension, e.g. n*x+y == X
. But we can verify with a couple of multidimensional ravel/unravel functions (as answered by @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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With