Friday , December 4 2026
Array Manipulation

Array Manipulation

Updated: 28 November 2026Level: BeginnerReading time: about 10 minutesNumPy 1.26+ / 2.x

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

NumPy Slicing and Indexing.

reshape

Example
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.

Output
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
(2, 6)

flatten and ravel

Example
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.

Output
[1 2 3 4] [1 2 3 4]

Transpose

Example
m = np.array([[1, 2, 3], [4, 5, 6]])
print(m.T)
print(m.shape, m.T.shape)
Output
[[1 4]
 [2 5]
 [3 6]]
(2, 3) (3, 2)

Add or Remove Dimensions

Example
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.

Output
(1, 3)
(3, 1)
(1, 3)
(3,)

append, insert and delete

Example
a = np.array([1, 2, 3])
print(np.append(a, [4, 5]))
print(np.insert(a, 1, 99))
print(np.delete(a, 0))
Output
[1 2 3 4 5]
[ 1 99  2  3]
[2 3]
Note: These create a new array every time. In a loop, collect values in a Python list and convert once at the end.

resize and repeat

Example
print(np.repeat([1, 2], 3))
print(np.tile([1, 2], 3))
Output
[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

  1. Convert a 1D array of 24 numbers into shape (2, 3, 4).
  2. 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.

Next: Combine and Split Arrays · Set Operations

About Machine Learning

Check Also

Exploratory Data Analysis (EDA) in Python: Step-by-Step Checklist

A step-by-step EDA checklist in pandas with tested outputs: shape, missing values, describe, value counts, groupby, correlations and charts.