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

Group data in a list with missing values as delimeter

I have an extended question following this question: I want to group data in a list with missing values as delimiter.

For example I have a list like this:

data = [1, 2, 3, nan, nan, nan, 4, 5, 6, nan, nan, 7, nan, 8, 9, nan, 0, 0, 'hello']
from math import nan

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

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)  

I got this results:

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

[[1, 2, 3], [4, 5, 6], [7], [8, 9], [0, 0], ['hello']]

Expected results:

[[1, 2, 3], [4, 5, 6], [7], [8, 9], [0, 0, 'hello']]

What I have tried by adjusting the groups variable but it did not work:

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

How can I adjust this in order to mix the value between integer and string?

>Solution :

You can use isinstance() in groupby key function:

from itertools import groupby

g = groupby(data, key=lambda v: isinstance(v, float))
groups = [list(a[1]) for a in g if not a[0]]
print(groups)

Prints:

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