1

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?

MathX
  • 136
  • 1
  • 6
  • Well, you could initialize a numpy array of Beans then just fill it in row by row. That would be faster. If you need something even faster, use numba – juanpa.arrivillaga Mar 16 '23 at 22:31

1 Answers1

1

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]]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91