Sum attributes of duplicate coordinates in python

Multi tool use
I am going through my coordinates data and I see some duplicate coordinates with different parameters due to certain preprocessing. I want to be able to merge the attributes corresponding to the matched coordinates and get the simplified results. To clarify what I mean here is an example:
The above data is read as follows: point (1.0, 8.0) has a value of 13 and (2.0, 3.0) has a value of 16. Notice that the second point and fourth point have the same coordinates but different attribute values. I want to be able to remove the duplicates from the lists of coordinates and sum the attributes so the results would be new lists:
24 is the sum of 16 and 8 from the second and fourth points with the same coordinates, therefore one point is kept and the values are summed.
I am not sure how to do this, I thought of using nested for loops of zips of the coordinates but I am not sure how to formulate it to sum the attributes.
Any help is appreciated!
I think that maintaining 3 lists is a bit awkward. Something like:
would put everything together in one place.
If you'd prefer to decompose it back into 3 lists:
Another option here is to use itertools.groupby
. But since this only groups consecutive keys, you'll have to first sort your coordinates.
First we can zip
them together to create tuples of the form (x, y, a)
. Then sort these by the (x, y)
coordinates:
Now we can groupby
the coordinates and sum the values:
And since zip
is it's own inverse, you can get New_X
, New_Y
, and New_A
via:
Of course, you can do this all in one line but I broke it up into pieces so that it's easier to understand.
you could put the (x,y)
coords in a dictionary:
Can use a dictionary
Try this list comprehension:
A dict
seems like a more appropriate data structure here. This will build one.
You can unpack these back into separate lists using:
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.