简体   繁体   中英

Tracing indices to original matrix in Python

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)]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM