Stack numpy arrays row-wise

Viewed 480

I'm trying to stack two numpy arrays row-wise. I could do it this way. is there a better way?

>>> a = np.arange(7, 13).reshape(2, 3)
>>> b = np.arange(1, 7).reshape(2, 3)
>>> x = np.row_stack((a[0],b[0]))
>>> y = np.row_stack((a[1],b[1]))
>>> z = np.stack((x, y))
>>> z
array([[[ 7,  8,  9],
        [ 1,  2,  3]],

       [[10, 11, 12],
        [ 4,  5,  6]]])
2 Answers

You can get the same with:

import numpy as np
a = np.arange(7, 13).reshape(2, 3)
b = np.arange(1, 7).reshape(2, 3)
z = np.stack((a, b), axis=1)
print(z)
# [[[ 7  8  9]
#   [ 1  2  3]]
# 
#  [[10 11 12]
#   [ 4  5  6]]]

You can use the numpy.row_stack method as follows:

a = np.arange(7, 13).reshape(2, 3)
b = np.arange(1, 7).reshape(2, 3)
x = np.row_stack((a[0],b[0]))
y = np.row_stack((a[1],b[1]))
z = np.row_stack([x, y])

Cheers.

Related