Array: add an ID value in a new column when two rows (in different arrays) are equals

Viewed 54

I'm a beginner in python. I have 2 arrays with 3 columns (ID, X_coord, Y_coord). In the two arrays, x and y of points are related to different IDs. My goal is to add a column and assign the same ID to the same point.

So let's say we have:

a = [[1, 4500, 5000], [2, 4600, 5100], [3, 4700, 5200]]
b = [[3, 4500, 5000], [1, 4600, 5100], [2, 4700, 5200]]

I would like to obtain something like:

a_new = [[1, 1, 4500, 5000], [2, 2, 4600, 5100], [3, 3, 4700, 5200]]
b_new = [[3, 1, 4500, 5000], [1, 2, 4600, 5100], [2, 3, 4700, 5200]]

I don't know how to implement this problem. I was thinking about sorting the rows with respect to x and y coordinates, but I would prefer to set up a for and when loop "for each row, when the values in the second and in the third rows are the same, set (in a fourth column) an increasing value.

Hope my explanation of the problem was exhaustive.

1 Answers

I hope I've understood your question right. To add new column with ID of first occurence of (X, Y) you can do:

a = [[1, 4500, 5000], [2, 4600, 5100], [3, 4700, 5200]]
b = [[3, 4500, 5000], [1, 4600, 5100], [2, 4700, 5200]]

# create a temporary dictionary with IDs:
tmp = {}
for id_, x, y in a:
    tmp[(x, y)] = tmp.get((x, y), id_)

# add new column to a and b
a = [[id_, tmp[(x, y)], x, y] for id_, x, y in a]
b = [[id_, tmp[(x, y)], x, y] for id_, x, y in b]

print(a)
print(b)

Prints:

[[1, 1, 4500, 5000], [2, 2, 4600, 5100], [3, 3, 4700, 5200]]
[[3, 1, 4500, 5000], [1, 2, 4600, 5100], [2, 3, 4700, 5200]]
Related