Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combine numpy arrays to list if first index value is similar

How to combine arrays inside 2D array to a list if the first index value is the same?

Say for example, this 2D array:

[[0 0]
 [0 3]
 [0 4]
 [1 1]
 [2 2]
 [3 0]
 [3 3]
 [3 4]
 [4 0]
 [4 3]
 [4 4]]

How will I make it to something like this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[[0, 0, 3, 4], [1 1], [2 2], [3 0 3 4], [4 0 3 4]]

When converting from numpy to list, I need it to be optimized as there are thousands of rows on my end.

Any suggestion is much appreciated. The end goal is I want the second index value to be combined together.

Also, take into consideration if ever the first index value is not in ascending order.

>Solution :

You can do it like that:

my_list = [
    [0, 0],
    [0, 3],
    [0, 4],
    [1, 1],
    [2, 2],
    [3, 0],
    [3, 3],
    [3, 4],
    [4, 0],
    [4, 3],
    [4, 4]
    ]

from collections import defaultdict

d = defaultdict(list)
for i, j in my_list:
    d[i].append(j)

combined = [[i]+l for i,l in d.items()]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading