Numpy: Concatenate arrays

20 August 2020

Code

# Import library
import numpy as np

# Create arrays
x = np.array([[1,2],[3,4]])
y = np.array([[10,20],[30,40]])

print("x:\n", x)
print('shape:',x.shape, 'n')
print("y:\n", y)
print('shape:',y.shape, 'n')
x:
 [[1 2]
 [3 4]]
shape: (2, 2) 

y:
 [[10 20]
 [30 40]]
shape: (2, 2)

.

Using .concatenate():

Note: .concatenate() with axis=0 is same as .vstack() and axis=1 is same as .hstack()

# Concatenate
ch = np.concatenate((x,y), axis = 0)
cv = np.concatenate((x,y), axis = 1)
cn = np.concatenate((x,y), axis = None)

# Output
print("Concatenate (axis=0):\n", ch)
print('shape:',ch.shape, '\n')
print("Concatenate (axis=1):\n", cv)
print('shape:',cv.shape, '\n')
print("Concatenate (axis=None):\n", cn)
print('shape:',cn.shape, '\n')
Concatenate (axis=0):
 [[ 1  2]
 [ 3  4]
 [10 20]
 [30 40]]
shape: (4, 2) 

Concatenate (axis=1):
 [[ 1  2 10 20]
 [ 3  4 30 40]]
shape: (2, 4) 

Concatenate (axis=None):
 [ 1  2  3  4 10 20 30 40]
shape: (8,)

.

Using .hstack():

Note: Same as .concatenate() with axis=1

# Stack
hs = np.hstack((x,y))

# Output
print("hstack:n", hs)
print('shape:',hs.shape, 'n')
hstack:
 [[ 1  2 10 20]
 [ 3  4 30 40]]
shape: (2, 4) 

.

Using .vstack():

Note: Same as .concatenate() with axis=0

# Stack
vs = np.vstack((x,y))

# Output
print("vstack:n", vs)
print('shape:',vs.shape, 'n')
vstack:
 [[ 1  2]
 [ 3  4]
 [10 20]
 [30 40]]
shape: (4, 2)






Any errors in code above?
Please send a message.