How to stack uneven numpy arrays?

Viewed 175

how can I stack the elements from the same respective index from each array in a list of arrays?

arrays = [np.array([1,2,3,4,5]),
          np.array([6,7,8,9]),
          np.array([11,22,33,44,55]),
          np.array([2,4])]

output = [[1,6,11,2],
          [2,7,22,4],
          [3,8,33],
          [4,9,44],
          [5,55]]

arrays is a list of arrays of uneven lengths. The output has a first array (don't mind if it's a list too) that contains all possible index 0s from each array. The next array within output contains all possible index 1s and so on...

Closest thing I can find (but requires same shape arrays) is:

a = np.array([1, 2, 3])
b = np.array([2, 3, 4])
np.stack((a, b), axis=-1)
# which gives
array([[1, 2],
       [2, 3],
       [3, 4]])

Thanks.

2 Answers

You could just wrap it in a DataFrame first:

arr = pd.DataFrame(arrays).values.T

Output:

array([[ 1.,  6., 11.,  2.],
       [ 2.,  7., 22.,  4.],
       [ 3.,  8., 33., nan],
       [ 4.,  9., 44., nan],
       [ 5., nan, 55., nan]])

Though if you really want it with different sizes, go with:

arr = [x.dropna().values for _, x in pd.DataFrame(arrays).iteritems()]                                             

Output:

[array([ 1,  6, 11,  2]),
 array([ 2,  7, 22,  4]),
 array([ 3.,  8., 33.]),
 array([ 4.,  9., 44.]),
 array([ 5., 55.])]

This gets you close. You can't really have a 2D sparse array as shown in your example output.

import numpy as np

arrays = [np.array([1,2,3,4,5]),
          np.array([6,7,8,9]),
          np.array([11,22,33,44,55]),
          np.array([2,4])]

maxx = max(x.shape[0] for x in arrays)
for x in arrays:
    x.resize(maxx,refcheck=False)
output = np.stack(arrays, axis=1)
print(output)
C:\tmp>python x.py
[[ 1  6 11  2]
 [ 2  7 22  4]
 [ 3  8 33  0]
 [ 4  9 44  0]
 [ 5  0 55  0]]
Related