This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

Stacking arrays

You can also concatenate and stack multiple existing arrays. Explore the output in the examples below. I think they should be pretty self-explanatory.

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

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

print(np.concatenate((a, b.T), axis=1))
## [[1 2 5]
##  [3 4 6]]
c = np.array([1, 2, 3])
d = np.array([4, 5, 6])

print(np.stack((c, d), axis=0)) 
## [[1 2 3]
##  [4 5 6]]

print(np.stack((c, d), axis=1)) 
## [[1 4]
##  [2 5]
##  [3 6]]

Again, there are specialised versions of np.stack():

  • np.vstack(tuple): same as np.stack(tuple, axis=0)
  • np.hstack(tuple): same as np.stack(tuple, axis=1)
  • np.dstack(tuple): same as np.stack(tuple, axis=2)

Repeating an array

You can also repeat an array easily with np.repeat().

print(np.repeat(0, 2))
## [0 0]

x = np.array([[1, 2],[3, 4]])
print(x)
## [[1 2]
##  [3 4]]

print(np.repeat(x, 2))
## [1 1 2 2 3 3 4 4]

print(np.repeat(x, 2, axis=0))
## [[1 2]
##  [1 2]
##  [3 4]
##  [3 4]]

print(np.repeat(x, 2, axis=1))
## [[1 1 2 2]
##  [3 3 4 4]]

# You can also specify the number of repeats individually
print(np.repeat(x, [1, 2], axis=0))
## [[1 2]
## [3 4]
## [3 4]]

print(np.repeat(x, [3, 2], axis=0))
## [[1 2]
##  [1 2]
##  [1 2]
##  [3 4]
##  [3 4]]