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

I want to group data in a list with missing values as delimiter

I have a sample data like this:

data = [1,2,3,nan,nan,nan,4,5,6,nan,nan,7,nan,8,9]

I want results like this:

group1 = [1,2,3]
group2 = [4,5,6]
group3 = [7]
group4 = [8,9]

But in fact I have a lot of information.
can you help me ?

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

>Solution :

Every time you want to group something, you probably want to go for itertools.groupby or collections.defaultdict:

from math import nan

data = [1, 2, 3, nan, nan, nan, 4, 5, 6, nan, nan, 7, nan, 8, 9]

from itertools import groupby

g = groupby(data, key=type)  # group by type of the data, int != float

groups = [list(a[1]) for a in g if a[0] != float]  

print(groups)  

Output:

[[1, 2, 3], [4, 5, 6], [7], [8, 9]]
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