Track index changes in numpy.reshape

When used numpy.reshapein Python, is there a way to track index changes?

For example, if a numpy array with a form is (m,n,l,k)converted to an array with a form (m*n,k*l); Is there a way to get the starting index ( [x,y,w,z]) for the current index [X,Y]and vice versa?

+4
source share
2 answers

Yes, this is called ravelingand unraveling. For example, you have two arrays:

import numpy as np

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

let's say you want to index an element (10, 52)(equivalent arr2[10, 52]), 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)
+4
source

, . 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)
+1

Source: https://habr.com/ru/post/1667704/


All Articles