Home > database >  Extracting node indices in an array in Python
Extracting node indices in an array in Python

Time:07-02

I want to extract indices in nodes corresponding to node numbers mentioned in the array I2. The current and expected outputs are presented.

import numpy as np
nodes={(0, 0): 1,
 (0, 1): 2,
 (1, 0): 3,
 (1, 1): 4}

I2=np.array([[1,2],[1,3],[2,4],[3,4]])

I3=[[i,i] in I2 for i in nodes]
print("I3 =",[I3])

The current output is

[False, False, False, False]

The expected output is

I3=np.array([[(0,0),(0,1)],[(0,0),(1,0)],[(0,1),(1,1)],[(1,0),(1,1)]])

CodePudding user response:

You can first reverse dictionary then do like below :

import numpy as np
nodes={(0, 0): 1,(0, 1): 2,(1, 0): 3,(1, 1): 4}
rvs_nodes = {v:k for k,v in nodes.items()}

I2=np.array([[1,2],[1,3],[2,4],[3,4]])

I3 = [[rvs_nodes[node[0]], rvs_nodes[node[1]]] for node in I2]
print("I3 =",I3)

Output:

I3 = [[(0, 0), (0, 1)], [(0, 0), (1, 0)], [(0, 1), (1, 1)], [(1, 0), (1, 1)]]
  • Related