I have a 2-D list of sublists of different lengths, I need to covert the list to a numpy array such that all the remaining values of shorter sublists are filled with -1, and I am looking for an efficient way to do this.
For example I have 2-D list x:
x = [
[0,2,3],
[],
[4],
[5,6]]
I want to get a numpy array that look like this:
>>> array_x
array([[ 0, 2, 3],
[-1, -1, -1],
[ 4, -1, -1],
[ 5, 6, -1]])
The basic way to do it is to create an array of -1s and then loop over the 2D list to fill in the remaining values, like this:
n_rows = len(x)
n_cols = max(len(ele) for ele in x)
new_array = np.ones((n_rows, n_cols)) * -1
for i, row in enumerate(x):
for j, ele in enumerate(row):
new_array[i, j] = ele
But is there a more efficient solution?