Home > other >  Tracing indices to original matrix in Python
Tracing indices to original matrix in Python

Time:04-18

I am trying to trace the indices of A2 with respect to A1. But I get an error. The desired output is attached.

import numpy as np
A1 = np.array([[0.3, 1.2, 2],
     [3, 4, 5]]) # Shape 2 rows & 3 columns

A2 = np.array([0.3,1.2])
A=list(zip(*np.unravel_index(A2, np.array(A1).shape)))
print([A])

Error:


  File "<__array_function__ internals>", line 5, in unravel_index

TypeError: only int indices permitted

Desired output:

[(0,0),(0,1)]

CodePudding user response:

This returns the desired list of tuples:

A = [tuple(np.array(np.where(A1 == a)).ravel().tolist()) for a in A2]

For each element a in A2, it finds the index in A1 using np.where. Then it converts the index to a tuple using ravel, tolist and tuple. Each index is automatically in the same list.

  • Related