Python Central HubSign in

Data Analytics with Python / Phase 2: Numerical Computing NumPy

Staking and Splitting Arrays

Combine arrays using hstack/vstack/concatenate and split arrays using split/hsplit/vsplit in NumPy.

Combining arrays

np.concatenate

Concatenate along an axis.

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

For 2D arrays:

Python
import numpy as np
 
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
 
print(np.concatenate([a, b], axis=0))  # stack rows
print(np.concatenate([a, b], axis=1))  # stack cols

np.vstack and np.hstack

Python
import numpy as np
 
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
 
print(np.vstack([a, b]))
print(np.hstack([a, b]))

np.stack (adds a new axis)

Unlike concatenate, stack creates a brand-new axis instead of joining along an existing one.

Python
import numpy as np
 
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
 
print(np.stack([a, b], axis=0).shape)  # (2, 3)
print(np.stack([a, b], axis=1).shape)  # (3, 2)
sketch Stacking two rows, then splitting back apart p5.js
vstack joins two 1D arrays into rows of a matrix; split cuts a matrix back into the original pieces.

Splitting arrays

np.split

Python
import numpy as np
 
arr = np.arange(10)
a, b = np.split(arr, [6])
print(a)
print(b)

np.hsplit and np.vsplit

Python
import numpy as np
 
mat = np.arange(16).reshape(4, 4)
left, right = np.hsplit(mat, 2)
print(left)
print(right)
 
top, bottom = np.vsplit(mat, 2)
print(top)
print(bottom)
diagram Stack vs concatenate vs split mermaid
Stacking functions join arrays along rows, columns, or a brand-new axis; split undoes that join.

Choosing the right joining function

Real data rarely arrives in one array. You might load one file per month, compute features in separate steps, or need to add a new column to an existing table. NumPy gives you several joining functions, and they differ mainly in whether they join along an existing axis or create a new one.

  • np.concatenate is the general tool. You pass a list of arrays and an axis. The arrays must match in every dimension except the one you join along.
  • np.vstack is shorthand for joining rows (axis 0), and np.hstack for joining columns (axis 1).
  • np.stack creates a brand-new axis, so the inputs must all have identical shapes.
  • np.column_stack turns 1D arrays into the columns of a 2D array.

The most common beginner surprise is with 1D arrays. np.hstack([a, b]) on two length-3 arrays gives one length-6 array, while np.vstack([a, b]) gives a 2 by 3 matrix. A 1D array has only one axis, so "horizontal" just means "end to end".

A worked example: adding a row and a column

Python
import numpy as np
 
scores = np.array([[1, 2], [3, 4]])
new_row = np.array([[5, 6]])
 
table = np.vstack([scores, new_row])
print(table)
# [[1 2]
#  [3 4]
#  [5 6]]
 
ids = np.array([[10], [20], [30]])
table = np.hstack([ids, table])
print(table)
# [[10  1  2]
#  [20  3  4]
#  [30  5  6]]

The new row must have the same number of columns as the table, and the new column must have the same number of rows. Note that ids is written as a column (shape 3 by 1). A plain 1D array of length 3 would fail with hstack here, because its dimensions would not match. np.column_stack([ids_1d, table]) is a handy alternative that accepts 1D input.

Splitting into equal or unequal parts

np.split(arr, 5) cuts into five equal pieces and raises an error if the length is not divisible by five. When you need "as equal as possible", use np.array_split:

Python
import numpy as np
 
arr = np.arange(10)
for part in np.array_split(arr, 3):
    print(part)
# [0 1 2 3]
# [4 5 6]
# [7 8 9]

Passing a list of indices, as in np.split(arr, [6]), means "cut before these positions", which is ideal for a train and test split of ordered data.

Common mistakes

  • Shape mismatches. Joining a 2 by 2 array with a 3 by 3 array along axis 0 raises ValueError because the column counts differ.
  • Forgetting the brackets. The functions take a list or tuple of arrays: np.concatenate([a, b]), not np.concatenate(a, b).
  • Confusing concatenate with stack. Concatenating two length-3 arrays gives length 6; stacking them gives shape (2, 3).
  • Expecting a copy to update the original. Joining always makes a new array. Splits, in contrast, return views, so editing a piece can modify the original data.

When to use each

Use vstack when new observations arrive, hstack or column_stack when you add features, stack when you are building a batch of equally shaped items such as images, and the split functions when you divide data into folds, chunks or train and test parts.

Check your understanding

quizCheck yourself
  1. For two 1D arrays a and b of length 3, what do np.hstack([a, b]) and np.vstack([a, b]) produce?

    Show answer

    A โ€” A length-6 array and a 2 by 3 matrix โ€” A 1D array has only one axis, so hstack joins end to end into length 6, while vstack stacks them as two rows.

  2. What is np.stack([a, b], axis=1).shape for two length-3 arrays?

    Show answer

    C โ€” (3, 2) โ€” stack creates a brand-new axis. With axis=1 the new axis goes second, giving (3, 2). With axis=0 the shape would be (2, 3).

  3. What does np.array_split(np.arange(10), 3) return?

    Show answer

    B โ€” Parts of lengths 4, 3 and 3 โ€” array_split cuts as evenly as possible, giving [0 1 2 3], [4 5 6] and [7 8 9]. np.split would raise an error for 3 equal pieces.

  4. What are the part lengths from a, b = np.split(np.arange(10), [6])?

    Show answer

    B โ€” 6 and 4 โ€” The list gives positions to cut before, so the first piece holds indices 0 to 5 (6 items) and the second holds the remaining 4.

Next

Continue to: NumPy Random Module for generating reproducible random numbers and sampling.

๐Ÿงช Try It Yourself

Exercise 1 โ€“ Stack Two Rows

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 2 โ€“ Split at an Index

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 3 โ€“ New Axis with stack

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Was this page helpful?

Let us know how we did