import numpy as np

Reshaping NumPy ArraysΒΆ

Reshaping changes the dimensions of an array without altering its data. The .shape attribute tells you the current dimensions (e.g., (12,) for a 1D array of 12 elements), and .reshape() creates a new view with different dimensions. The total number of elements must remain the same – a 12-element array can become (3, 4), (2, 6), (2, 3, 2), etc. Using -1 for one dimension tells NumPy to calculate it automatically. Flattening with .reshape(-1) converts any multi-dimensional array back to 1D. Reshaping is essential in ML pipelines – for example, converting a batch of images from (batch, height, width, channels) to (batch, features) for a dense layer.

# Create 1-D Numpy Array and Get Shape
np1 = np.array([1,2,3,4,5,6,7,8,9,10,11,12])
print(np1)
print(np1.shape)

2-D Array ShapeΒΆ

A 2D array’s shape is reported as (rows, columns). Here, a 2x6 array has shape (2, 6) – 2 rows and 6 columns containing 12 total elements.

Reshaping from 1-D to 2-DΒΆ

.reshape(3, 4) transforms a flat 12-element array into a 3x4 matrix. The elements fill in row-major order (C order) by default – the first 4 elements become row 0, the next 4 become row 1, and so on.

# Reshape 3-D
np4 = np1.reshape(2,3,2)
print(np4)
print(np4.shape)
# Flatten to 1-D
np5 = np4.reshape(-1)
print(np5)
print(np5.shape)