ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

NumPy Tutorial• 7 min read

Array Reshaping, Flattening, Stacking & Splitting

reshape(-1), flatten vs ravel, vstack, hstack, and concatenate

Manipulating array geometries is a daily task in machine learning pipelines, from flattening image tensors to stacking feature vectors.

Reshaping and Dimension Ingestion

arr.reshape(new_shape): Changes dimensions without altering data. Using -1 in one dimension causes NumPy to automatically infer that dimension size based on arr.size.

arr.ravel() vs arr.flatten(): ravel() returns a flattened 1D view where possible; flatten() always allocates a new copy.

np.vstack((a, b)) and np.hstack((a, b)): Stacks arrays vertically (row-wise) or horizontally (column-wise).

Reshaping and Stacking Arrays
import numpy as np

# 12 elements into a 3x4 matrix
data = np.arange(12).reshape(3, 4)
print("3x4 Matrix:
", data)

# Automatically infer column count
auto_reshaped = data.reshape(2, -1)
print("Auto-inferred 2x6:
", auto_reshaped)

# Horizontal stacking
features_a = np.array([[1, 2], [3, 4]])
features_b = np.array([[50], [60]])
combined = np.hstack((features_a, features_b))
print("Combined features (hstack):
", combined)
reshape(-1) automatically computes the remaining dimension size.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What is the key performance difference between `arr.ravel()` and `arr.flatten()`?