I have a 2D python list, with varying lengths. I would like to convert this list to a numpy array, prepending or appending a value (e.g. 0) to lists shorter than the longest list.
Creating a ragged array doesn't really work, since I need the shape (and other functions) of the array. Additionally I think ragged arrays would be slower, though I have no evidence for this.
The following code does what I want to do, but I was hoping for a more efficient solution:
import numpy as np
python_list = [[1,2], [1,2,3], [1,2,3,4,5,6,7,8,9]]
N = len(python_list)
M = max(map(len, python_list))
value = 0
arr = np.full((N, M), value)
for i, l in zip(range(N), python_list):
arr[i,:len(l)] = l # append value
arr[i,-len(l):] = l # prepend value
References: