'concatenate arrays of different lengths into one multidimensional array

I know that you cant stack or concatenate arrays of different lenghths in NumPy as all matrices need to be rectangular, but is there any other way to achieve this?

For example:

a = [1, 2 ,3]
b = [9, 8]

Stacking them would give:

c = [[1, 2, 3]
     [9, 8]]

alternatively if there is no way to create the above how could I write a function to get this: (0 in place of missing element to fill matrix)?

c = [[1, 2, 3]
     [9, 8, 0]]


Solution 1:[1]

This code worked for me:

a = [1, 2 ,3]
b = [9,8]
while len(b) != len(a):
    if len(b) > len(a):
        a.append(0)
    else:
        b.append(0)
final = np.array([a,b])
print(final)

The code is self explanatory, but I will try my best to give a valid explanation: We take two lists (say a and b) and we compare there lengths, if they are unequal we add element (in this case 0) to the one whose length is lower, this loops until their lengths are equal, then it simply converts them into a 2D array in numpy

Also you can replace 0 with np.NaN if you want NaN values

Solution 2:[2]

I think what you are looking for is:

In:

from itertools import zip_longest
a = [1, 2 ,3]
b = [9, 8]
c = np.array(list(zip_longest(*[a,b])),dtype=float).transpose()
print(c)

Out:

[[ 1.  2.  3.]
 [ 9.  8. nan]]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aryan Garg
Solution 2 jeremy