Array manipulation means changing the shape or layout of an array without changing its data: reshaping, flattening, transposing, adding dimensions, and inserting or deleting elements. Getting shapes right is essential in machine learning.
Prerequisites
reshape
import numpy as np
a = np.arange(12)
print(a.reshape(3, 4))
print(a.reshape(2, -1).shape)
Explanation: The total number of elements must stay the same (12 = 3 × 4). -1 lets NumPy work out that dimension.
[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] (2, 6)
flatten and ravel
m = np.array([[1, 2], [3, 4]])
print(m.flatten(), m.ravel())
Explanation: Both make a 1D array. flatten() always copies; ravel() returns a view when possible.
[1 2 3 4] [1 2 3 4]
Transpose
m = np.array([[1, 2, 3], [4, 5, 6]])
print(m.T)
print(m.shape, m.T.shape)
[[1 4] [2 5] [3 6]] (2, 3) (3, 2)
Add or Remove Dimensions
x = np.array([1, 2, 3])
print(x[np.newaxis, :].shape) # row vector
print(x[:, np.newaxis].shape) # column vector
print(np.expand_dims(x, 0).shape)
print(np.squeeze(np.zeros((1, 3, 1))).shape)
Explanation: scikit-learn needs 2D input, so a single feature must be reshaped to (n, 1). Deep learning often needs an extra batch dimension.
(1, 3) (3, 1) (1, 3) (3,)
append, insert and delete
a = np.array([1, 2, 3])
print(np.append(a, [4, 5]))
print(np.insert(a, 1, 99))
print(np.delete(a, 0))
[1 2 3 4 5] [ 1 99 2 3] [2 3]
resize and repeat
print(np.repeat([1, 2], 3))
print(np.tile([1, 2], 3))
[1 1 1 2 2 2] [1 2 1 2 1 2]
Common Errors
| Problem | Cause and fix |
|---|---|
ValueError: cannot reshape array of size 12 into shape (5,3) |
The new shape must have the same number of elements. |
scikit-learn: Expected 2D array, got 1D array |
Use X.reshape(-1, 1). |
Practice Exercises
- Convert a 1D array of 24 numbers into shape (2, 3, 4).
- Turn a (28, 28) image into a 784-length vector.
Interview Questions
Q: flatten vs ravel?
flatten always returns a copy; ravel returns a view if possible.
Q: What does -1 do in reshape?
Infers that dimension from the others.
Summary
Use reshape, ravel/flatten, .T, newaxis/expand_dims and squeeze to change shapes; append/insert/delete return new arrays.
Machine Learning Tutorials, Courses and Certifications