The problem I have is difficult to describe in general, so I describe the actual problem.
I have points in an image, which have a specific ID. Additionally, I have a larger amount of points in another image, some of which having the same ID. I want to link to the points in the first image. Linking should be over the position in the tuple. ID1
doesn't not have to be in position 1, but the corresponding points should be the same position in both tuples.
ID1 = (1, 2, 3, 4)
ID2 = (5, 3, 1, 2, 4)
points1= ((1,2), (1, 4), (3,5), (7,8))
points2= ((1,3), (2, 4), (2,5), (4,8), (3,9))
What I need is a sorted output like the following
points_1_outpout = ((1,2), (1, 4), (3,5), (7,8))
points_2_output = ((2,5), (4, 8), (2,4), (3,9))
What I did was: (and it is ugly and not really working, because I can't expect to have increasing IDs without "holes")
import numpy as np
ID1 = (1, 2, 3, 4)
ID2 = (5, 3, 1, 2, 4)
ID1 = np.asarray(ID1)
Id2 = np.asarray(ID2)
points1= ((1,2), (1, 4), (3,5), (7,8))
points2= ((1,3), (2, 4), (2,5), (4,8), (3,9))
points1 = np.asarray(points1)
points2 = np.asarray(points2)
##points_1_outpout = ((1,2), (1, 4), (3,5), (7,8))
###points_2_output = ((2,5), (4, 8), (2,4), (3,9))
ID1sort, Corner1sort = zip(*sorted(zip(ID1, points1)))
ID2sort, Corner2sort = zip(*sorted(zip(ID2, points2)))
Probably not optimal but you can do:
d1 = dict(sorted(zip(ID1, points1)))
d2 = dict(sorted(zip(ID2, points2)))
keys = set(d1).intersection(d2)
out1 = [v for k, v in d1.items() if k in keys]
out2 = [v for k, v in d2.items() if k in keys]
Output:
>>> out1
[(1, 2), (1, 4), (3, 5), (7, 8)]
>>> out2
[(2, 5), (4, 8), (2, 4), (3, 9)]
If you use Pandas
:
import pandas as pd
sr1 = pd.Series(points1, index=ID1, name='P1')
sr2 = pd.Series(points2, index=ID2, name='P2')
out = pd.concat([sr1, sr2], axis=1).dropna().to_dict('list')
Output:
>>> out
{'P1': [(1, 2), (1, 4), (3, 5), (7, 8)],
'P2': [(2, 5), (4, 8), (2, 4), (3, 9)]}