Map the indices of 2d array into 1d array in Python

Question:

Say I have a square 2d array (mat) and a 1d array (arr) which is the same length as the flattened 2d array (the values inside are different). Given the row and column index of the 2d array, how can I map it into the 1d array index to give the value of the same position as the 2d array? Here’s a small (4 element) example of what I mean:

mat = np.array([[6, 7], [8, 9]])
arr = np.array([1, 2, 3, 4])

The mapping I’m looking for is:

mat[0,0] -> arr[0]
mat[0,1] -> arr[1]
mat[1,0] -> arr[2]
mat[1,1] -> arr[3]

Note that I can’t match with values as they aren’t the same so the mapping would be on the index itself.

Asked By: statwoman

||

Answers:

> arr = np.random.randint(0, 10, size=(9,))
> arr
array([5, 7, 6, 5, 9, 6, 2, 0, 1])

> mat = np.random.randint(0, 10, size=(3,3))
> mat
array([[2, 8, 3],
       [1, 4, 6],
       [9, 2, 3]])

> idx = np.arange(len(arr)).reshape(mat.shape[0],mat.shape[1])
> idx
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

> mat[0, 0], arr[idx[0, 0]]
2, 5
Answered By: Woodford
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.