Pythonic method for stacking np.array's of different row length

Question:

Assume I have following multiple numpy np.array with different number of rows but same number of columns:

a=np.array([[10, 20, 30],
            [40, 50, 60],
            [70, 80, 90]])

b=np.array([[1, 2, 3],
            [4, 5, 6]])

I want to combine them to have following:

result=np.array([[10, 20, 30],
                 [40, 50, 60],
                 [70, 80, 90],
                 [1, 2, 3],
                 [4, 5, 6]])

Here’s what I do using for loop but I don’t like it. Is there a pythonic way to do this?

c=[a,b]
num_row=sum([x.shape[0] for x in c])
num_col=a.shape[1] # or b.shape[1]
result=np.zeros((num_row,num_col))
k=0
for s in c:
    for i in s:
        reult[k]=i
        k+=1

result=
array([[10, 20, 30],
       [40, 50, 60],
       [70, 80, 90],
       [1, 2, 3],
       [4, 5, 6]])
Asked By: doubleE

||

Answers:

Use numpy.concatenate(), this is its exact purpose.

import numpy as np
a=np.array([[10, 20, 30],
            [40, 50, 60],
            [70, 80, 90]])

b=np.array([[1, 2, 3],
            [4, 5, 6]])
result = np.concatenate((a, b), axis=0)

In my opinion, the most "Pythonic" way is to use a builtin or package rather than writing a bunch of code. Writing everything from scratch is for C developers.

Answered By: Michael Ruth
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.