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?
>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]]