Skip to main content

NumPy Reshaping and Combining Arrays: Reshape, Stack, and Concatenate

Calculating read time…

Reshaping lets you change the structure of your data without copying it — like rearranging furniture in a room to fit better. Combining arrays merges multiple datasets into one — perfect for building bigger pictures from smaller pieces! 🧩

Why Reshape Arrays?

Real data often comes in the "wrong" shape for your needs. Reshaping fixes that quickly and efficiently.

Most reshaping functions return a view — no data is copied, so it's fast and memory-friendly.

🟢 DO: Reshape early and often — it makes broadcasting, plotting, and analysis much easier!

Basic Reshaping with reshape()

reshape() changes the array's dimensions while keeping the data.

import numpy as np

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

# Reshape to 2 rows, 3 columns
matrix = arr.reshape(2, 3)
print("2x3 matrix:\n", matrix)

# Use -1 to let NumPy figure out one dimension
column = arr.reshape(-1, 1)  # Auto-calculates rows
print("Column vector shape:", column.shape)
2x3 matrix:
 [[1 2 3]
 [4 5 6]]
Column vector shape: (6, 1)

-1 is a lifesaver — use it when you know one dimension but not the other!

Flattening: ravel() vs flatten()

Turn any array back to 1D.

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

flat_ravel = matrix.ravel()   # Returns a view (preferred)
flat_flatten = matrix.flatten()  # Returns a copy

print("Ravel:", flat_ravel)
print("Flatten:", flat_flatten)
Ravel: [1 2 3 4 5 6]
Flatten: [1 2 3 4 5 6]
🟡 Tip: Prefer ravel() — it's faster and uses less memory since it's usually a view.

Transpose - Flip Dimensions

print("Original:\n", matrix)
print("Transposed:\n", matrix.T)
Original:
 [[1 2 3]
 [4 5 6]]
Transposed:
 [[1 4]
 [2 5]
 [3 6]]

Great for switching rows and columns!

Combining Arrays

concatenate() - Join Along Existing Axis

arr1 = np.array([[1, 2],
                 [3, 4]])

arr2 = np.array([[5, 6]])

# Join vertically (axis=0)
vertical = np.concatenate((arr1, arr2), axis=0)
print("Vertical:\n", vertical)

# Join horizontally (axis=1) — shapes must match on other axis
arr3 = np.array([[7], [8]])
horizontal = np.concatenate((arr1, arr3), axis=1)
print("Horizontal:\n", horizontal)
Vertical:
 [[1 2]
 [3 4]
 [5 6]]
Horizontal:
 [[1 2 7]
 [3 4 8]]

Stacking: vstack, hstack, dstack

# Vertical stack (like concatenate axis=0)
print("vstack:\n", np.vstack((arr1, arr2)))

# Horizontal stack
print("hstack:\n", np.hstack((arr1, arr3)))

# Depth stack (new axis)
depth = np.dstack((arr1, arr1 * 2))
print("dstack shape:", depth.shape)  # (2, 2, 2)

Real-World Example: Building a Complete Student Dataset

Combine marks from different terms and reshape for analysis.

# Term 1 marks (5 students, 3 subjects)
term1 = np.array([
    [85, 88, 92],
    [90, 76, 85],
    after[78, 92, 88],
    [92, 85, 79],
    [88, 90, 94]
])

# Term 2 marks (same students)
term2 = np.array([
    [87, 90, 91],
    [88, 78, 87],
    [80, 89, 90],
    [90, 87, 81],
    [89, 92, 93]
])

print("Term 1:\n", term1)
print("Term 2:\n", term2)

Combine Terms

# Stack along new axis (terms)
all_terms = np.stack((term1, term2), axis=0)  # Shape: (2, 5, 3)
print("All terms shape:", all_terms.shape)

# Average across terms
yearly_avg = np.mean(all_terms, axis=0)
print("Yearly averages:\n", np.round(yearly_avg, 1))
All terms shape: (2, 5, 3)
Yearly averages:
 [[86.  89.  91.5]
 [89.  77.  86. ]
 [79.  90.5 89. ]
 [91.  86.  80. ]
 [88.5 91.  93.5]]

Reshape for Different Views

# Flatten all marks for overall stats
all_marks = all_terms.ravel()
print("All marks mean:", np.mean(all_marks))

# Reshape to (students, subjects*2)
flattened_terms = all_terms.reshape(5, -1)  # 5 students, 6 scores
print("Flattened terms shape:", flattened_terms.shape)
All marks mean: 87.4
Flattened terms shape: (5, 6)

Splitting Arrays

# Split into 2 terms again
term1_split, term2_split = np.split(all_terms, 2, axis=0)
print("Split successful:", np.array_equal(term1, term1_split))
Split successful: True

Beginner Mistakes - Common Errors and How to Avoid Them

🔴 DON'T: Reshape with incompatible sizes — total elements must stay the same! (e.g., 6 elements → only 2x3, 3x2, etc.)
🔴 DON'T: Forget to provide arrays as a tuple in concatenate((arr1, arr2)) — single list won't work.
🔴 DON'T: Use flatten() when ravel() is enough — unnecessary copies slow things down.

Optimization Tips

🟢 DO: Use views (reshape, ravel, T) whenever possible — they're instant and memory-efficient.
🟢 DO: Use np.newaxis with stacking for precise control over new dimensions.

Real-World Use Cases

  • Image Processing: Reshape pixel arrays, stack channels (RGB)
  • Machine Learning: Flatten images for models, stack batches
  • Data Analysis: Combine datasets from multiple sources
  • Time Series: Stack periods for multi-dimensional analysis

Quick Summary 📝

  • reshape(): Change dimensions, use -1 for auto
  • ravel()/flatten(): 1D views/copies
  • T: Quick transpose
  • Combine: concatenate, stack, vstack/hstack
  • Split data with np.split

Reshaping and combining are essential skills — master them, and your data will always be in the perfect form! Happy coding! ✨

Comments