Learning Objectives – after this chapter you will be able to:
  • Join arrays with np.concatenate() along a chosen axis.
  • Stack arrays along a new axis with np.stack().
  • Use the helpers hstack, vstack and dstack.
  • Apply the shape rules for joining arrays.
Joining Arrays

Joining means putting the contents of two or more arrays into a single array. NumPy offers two ideas:

  • Concatenate – join along an existing axis (the number of dimensions stays the same).
  • Stack – join along a new axis (the result has one more dimension).
np.concatenate()
np.concatenate((arr1, arr2, ...), axis=0)
import numpy as np

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

m1 = np.array([[1, 2], [3, 4]])
m2 = np.array([[5, 6], [7, 8]])
print(np.concatenate((m1, m2), axis=0))   # add rows
print(np.concatenate((m1, m2), axis=1))   # add columns
Output
[1 2 3 4 5 6]
[[1 2]
 [3 4]
 [5 6]
 [7 8]]
[[1 2 5 6]
 [3 4 7 8]]

Shape rule: all arrays must have the same shape except along the joining axis.

import numpy as np

m1 = np.array([[1, 2], [3, 4]])        # shape (2, 2)
row = np.array([[9, 9, 9]])            # shape (1, 3)
try:
    np.concatenate((m1, row), axis=0)
except ValueError as e:
    print("ValueError raised: column counts differ")
print(np.concatenate((m1, np.array([[9, 9]])), axis=0))
Output
ValueError raised: column counts differ
[[1 2]
 [3 4]
 [9 9]]
np.stack()

np.stack() joins arrays of the same shape along a new axis.

import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
s0 = np.stack((a, b))           # axis=0 (default)
s1 = np.stack((a, b), axis=1)
print(s0, s0.shape)
print(s1, s1.shape)
Output
[[1 2 3]
 [4 5 6]] (2, 3)
[[1 4]
 [2 5]
 [3 6]] (3, 2)
hstack(), vstack() and dstack()
FunctionJoins
np.hstack()Horizontally – side by side (columns for 2-D; end to end for 1-D).
np.vstack()Vertically – one below the other (rows).
np.dstack()Depth-wise – along the third axis.
import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.hstack((a, b)))
print(np.vstack((a, b)))
d = np.dstack((a, b))
print(d, d.shape)
Output
[1 2 3 4 5 6]
[[1 2 3]
 [4 5 6]]
[[[1 4]
  [2 5]
  [3 6]]] (1, 3, 2)
Practical Example: Adding a Total Column
import numpy as np

marks = np.array([[78, 85], [62, 70], [90, 88]])
totals = marks.sum(axis=1).reshape(-1, 1)     # column vector
report = np.hstack((marks, totals))
print(report)
Output
[[ 78  85 163]
 [ 62  70 132]
 [ 90  88 178]]
Key Takeaways
  • concatenate joins along an existing axis; stack creates a new axis.
  • Arrays must match in every dimension except the joining axis.
  • hstack = side by side, vstack = one under another, dstack = depth.
Video : Array Join
Question / Answer (15 questions)

Answer : Joining means combining the contents of two or more arrays into a single array, either along an existing axis (concatenation) or along a new axis (stacking).

Answer : Concatenation (np.concatenate) joins arrays along an existing axis, so the number of dimensions is unchanged. Stacking (np.stack) joins arrays along a new axis, so the result has one more dimension.

Answer : np.concatenate((arr1, arr2, ...), axis=0). The arrays are passed as a tuple or list, and axis selects the joining direction (0 by default).

Answer : Along axis 0 the rows are added, giving a 4 × 2 array. Along axis 1 the columns are added, giving a 2 × 4 array.

Answer : All arrays must have the same number of dimensions and the same size in every dimension except the axis along which they are joined; otherwise ValueError is raised.

Answer : A new 2-D array [[1 2 3] [4 5 6]] with shape (2, 3), because the arrays are stacked along a new first axis.

Answer : [[1 4] [2 5] [3 6]] with shape (3, 2) – corresponding elements are paired along the new second axis.

Answer : All input arrays must have exactly the same shape.

Answer : For 1-D arrays it joins them end to end into one longer 1-D array. For 2-D arrays it places them side by side, adding columns (equivalent to concatenation along axis 1).

Answer : It stacks arrays vertically, one below the other, adding rows. Two 1-D arrays of length 3 become a 2 × 3 array.

Answer : dstack joins arrays along the third axis (depth). Two 1-D arrays of length 3 produce shape (1, 3, 2).

Answer : Compute row sums with marks.sum(axis=1), reshape them into a column with reshape(-1, 1), then join with np.hstack((marks, totals)).

Answer : np.vstack() or np.stack(..., axis=0); both place each array as a separate row.

Answer : No. It returns a new array containing copies of the data; the original arrays are unchanged.

Answer : Along axis 0 the column counts must match, but one has 2 columns and the other has 3, so NumPy raises ValueError.
MCQ Test : Check Your Understanding (5 questions)

Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.

Q1. Which function joins arrays along a NEW axis?

Show Answer

Correct Answer : B. np.stack
np.stack adds a new dimension.

Q2. Concatenating two (2, 3) arrays with axis=1 gives shape:

Show Answer

Correct Answer : C. (2, 6)
Columns are added: 3 + 3 = 6.

Q3. np.vstack((np.array([1, 2]), np.array([3, 4]))) returns:

Show Answer

Correct Answer : A. [[1 2] [3 4]]
vstack places each 1-D array as a row.

Q4. np.hstack on two 1-D arrays of length 3 gives an array of shape:

Show Answer

Correct Answer : D. (6,)
1-D arrays are joined end to end.

Q5. Which function joins along the third axis (depth)?

Show Answer

Correct Answer : C. np.dstack
dstack joins along axis 2.

Bibliography/References

The notes, questions and MCQs on this page are original explanations written for this course. The works listed below were consulted and are cited for attribution and further reading. Product names, logos and trademarks belong to their respective owners. Short quotations, where used, are marked and attributed.

  1. NumPy Developers. (n.d.). Array manipulation routines (concatenate, stack, split …). NumPy API Reference. https://numpy.org/doc/stable/reference/routines.array-manipulation.html
  2. NumPy Developers. (n.d.). NumPy quickstart. NumPy User Guide. https://numpy.org/doc/stable/user/quickstart.html
  3. NumPy Developers. (n.d.). NumPy: the absolute basics for beginners. NumPy User Guide. https://numpy.org/doc/stable/user/absolute_beginners.html
  4. VanderPlas, J. (2016). Python Data Science Handbook. O’Reilly Media. (Free online edition.) https://jakevdp.github.io/PythonDataScienceHandbook/