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

Making an array from lists of different sizes and filling the gaps with Nan in Python

Let’s say I have a list of lists, and they can have different sizes:

arr=list([[0. , 1.5, 3. , 0. , 1.5],[0. , 1.5, 3. ],[0., 1.33, 2.67, 4. ]])

I want to make this array numpy compatible and make a filled array based on the maximum length and fill the gaps with Nan:

arr_filled=list([[0. , 1.5, 3. , 0. , 1.5],[0. , 1.5, 3.,None,None ],[0., 1.33, 2.67, 4.,None ]])

My current method is to find the length of each list by map(len, arr) and then looping over lists and adding None until they all have the same size. Is there a faster and cleaner way to do 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

>Solution :

You can use itertools.zip_longest:

from itertools import zip_longest

arr = [[0.0, 1.5, 3.0, 0.0, 1.5], [0.0, 1.5, 3.0], [0.0, 1.33, 2.67, 4.0]]

arr_filled = [list(tpl) for tpl in zip(*zip_longest(*arr))]
print(arr_filled)

Prints:

[[0.0, 1.5, 3.0, 0.0, 1.5], [0.0, 1.5, 3.0, None, None], [0.0, 1.33, 2.67, 4.0, None]]
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