Master NumPy From Scratch

Learn NumPy fundamentals, arrays, indexing, slicing, data types, array operations, broadcasting, mathematical functions, statistics, random numbers, linear algebra, file handling, and practical projects through structured lessons.

COURSE SYLLABUS
1. NumPy Introduction and Installation
Introduction to NumPy NumPy Installation and Setup NumPy Environment and IDE Setup First NumPy Program
2. NumPy Arrays and Array Creation
NumPy Array Fundamentals Array Creation Functions Zeros, Ones and Identity Arrays Range and Linspace Arrays
3. NumPy Array Indexing and Slicing
One-Dimensional Array Indexing Array Slicing Techniques Two-Dimensional Array Indexing Boolean and Fancy Indexing
4. NumPy Data Types and Attributes
NumPy Data Types Array Shape, Size and Dimensions Data Type Conversion and Casting Array Inspection and Attributes
5. NumPy Array Shape and Reshaping
Reshape and Flatten Arrays Transpose and Axis Operations Stacking and Splitting Arrays Expand and Squeeze Dimensions
6. NumPy Array Operations and Broadcasting
Arithmetic Array Operations Comparison and Logical Operations Broadcasting Fundamentals Universal Functions and Vectorization
7. NumPy Mathematical and Statistical Functions
Mathematical Functions Aggregate and Statistical Functions Minimum, Maximum and Percentiles Rounding and Trigonometric Functions
8. NumPy Filtering and Sorting
Array Filtering and Conditions Sorting and Searching Arrays Unique Values and Set Operations Where, Select and Nonzero Functions
9. NumPy Copies and Views
Array Copies and Views Shallow and Deep Copy Concepts Memory Layout and Contiguity Array Iteration and Memory Efficiency
10. NumPy Random Number Generation
Random Generator Fundamentals Random Integers and Sampling Probability Distributions Random Seeds and Simulation
11. NumPy Linear Algebra
Vectors and Matrices Matrix Multiplication and Dot Product Determinants and Matrix Inverse Eigenvalues and Linear Equations
12. NumPy File Input and Output
Importing and Exporting Text Files CSV Data with NumPy Binary Files and NPY Format NPZ Files and Data Persistence
13. NumPy Practical Projects
Student Marks Analysis Project Sales Data Analysis Project Random Simulation Project Image Array Processing Project
14. NumPy Practice and Assessment
NumPy Beginner Practice NumPy Intermediate Exercises NumPy Advanced Challenges Final NumPy Assessment

Reshape and Flatten Arrays

Learn how to change the structure of NumPy arrays, convert one-dimensional arrays into multidimensional arrays, and flatten arrays into a single dimension for analysis and processing.

1. Learning Objectives

By the end of this lesson, you will be able to:

  • Understand the purpose of reshaping arrays.
  • Use the reshape() method.
  • Convert one-dimensional arrays into two-dimensional and three-dimensional arrays.
  • Use -1 to infer a dimension automatically.
  • Flatten arrays using flatten() and ravel().
  • Understand the difference between flattening and reshaping.
  • Avoid common shape mismatch errors.

2. What Is Array Reshaping?

Array reshaping means changing the arrangement or dimensions of elements without changing the total number of elements. NumPy provides the reshape() method for this purpose.

For example, an array containing six elements can be arranged as a single row, two rows with three columns, or three rows with two columns.

import numpy as np values = np.array([10, 20, 30, 40, 50, 60]) print(values.shape) # (6,)
Important: The example above should use separate lines in Python. The correct executable version is shown below.
import numpy as np values = np.array([10, 20, 30, 40, 50, 60]) print(values.shape) # (6,) print(values.reshape(2, 3))
Original: (6,) Reshaped: (2, 3) 10 20 30 40 50 60 10 20 30 40 50 60 Same six elements, different arrangement

Reshaping changes the array's structure, not its total element count.

3. Using reshape()

The reshape() method accepts the desired dimensions. The product of the requested dimensions must equal the number of elements in the original array.

import numpy as np values = np.array([1, 2, 3, 4, 5, 6]) matrix_2x3 = values.reshape(2, 3) matrix_3x2 = values.reshape(3, 2) matrix_1x6 = values.reshape(1, 6) print(matrix_2x3) print(matrix_3x2) print(matrix_1x6)

Possible Results

Expression Shape Structure
values.reshape(2, 3) (2, 3) Two rows and three columns.
values.reshape(3, 2) (3, 2) Three rows and two columns.
values.reshape(1, 6) (1, 6) One row and six columns.
values.reshape(6, 1) (6, 1) Six rows and one column.
Remember: A one-dimensional array with shape (6,) is different from a two-dimensional row array with shape (1, 6).

4. Reshaping into Three Dimensions

NumPy can reshape arrays into three or more dimensions, provided the requested shape contains the same total number of elements. Three-dimensional arrays are often used to represent batches, image channels, or grouped datasets.

import numpy as np values = np.arange(1, 13) three_d = values.reshape(2, 2, 3) print(three_d) print("Shape:", three_d.shape) print("Dimensions:", three_d.ndim) print("Elements:", three_d.size)

Expected output:

[[[ 1 2 3] [ 4 5 6]] [[ 7 8 9] [10 11 12]]] Shape: (2, 2, 3) Dimensions: 3 Elements: 12

Interpreting the Shape

  • The first dimension has 2 groups.
  • Each group has 2 rows.
  • Each row has 3 elements.
  • The total number of elements is 2 × 2 × 3 = 12.

5. Using -1 for Automatic Dimension Inference

NumPy allows one dimension in reshape() to be specified as -1. NumPy calculates that dimension automatically using the total number of elements and the other requested dimensions.

import numpy as np values = np.arange(1, 13) result_2d = values.reshape(3, -1) result_column = values.reshape(-1, 1) print(result_2d.shape) # (3, 4) print(result_column.shape) # (12, 1)

In the first example, twelve elements arranged in three rows require four columns. In the second example, the result has twelve rows and one column.

Important: Only one dimension can be inferred with -1 in a reshape operation. NumPy cannot infer the shape if the requested dimensions are ambiguous or incompatible.

6. What Is Array Flattening?

Flattening converts a multidimensional array into a one-dimensional array. It is useful when a task requires all elements in a single sequence, such as preparing values for certain analysis workflows.

import numpy as np matrix = np.array([ [10, 20, 30], [40, 50, 60] ]) flat = matrix.flatten() print(flat) print(flat.shape)

Expected output:

[10 20 30 40 50 60] (6,)
2D Array 1D Array 10 20 30 40 50 60 10 20 30 40 50 60 Six elements become one linear sequence

Flattening reduces the array to one dimension.

7. Using flatten()

The flatten() method returns a flattened copy of the array. Changes made to the returned array do not change the original array's elements.

import numpy as np matrix = np.array([ [1, 2, 3], [4, 5, 6] ]) flat = matrix.flatten() flat[0] = 999 print("Flattened array:", flat) print("Original array:") print(matrix)

Expected output:

Flattened array: [999 2 3 4 5 6] Original array: [[1 2 3] [4 5 6]]
Key point: Use flatten() when you specifically need an independent one-dimensional copy.

8. Using ravel()

The ravel() method also returns a one-dimensional representation of an array. It often returns a view when possible, but it may return a copy depending on the array's layout and requested order.

import numpy as np matrix = np.array([ [1, 2, 3], [4, 5, 6] ]) flat = matrix.ravel() print(flat) print(flat.shape)

Expected output:

[1 2 3 4 5 6] (6,)

If ravel() returns a view, changes to that view may affect the original array. Do not rely on it always returning a view or always returning a copy.

9. flatten() vs ravel()

Feature flatten() ravel()
Result One-dimensional array. One-dimensional array.
Copy or view Returns a copy. Returns a view when possible; otherwise a copy.
Memory use Allocates a separate array for the result. May avoid a copy when possible.
Use when An independent flattened array is required. A flattened representation is needed and avoiding a copy may help.
Remember: If you need to guarantee that changes cannot affect the original array, flatten() is the straightforward choice.

10. Reshape Order: C and F

NumPy supports different element-reading orders when reshaping or flattening. The default order, 'C', follows row-major indexing. The 'F' order follows column-major indexing.

import numpy as np values = np.array([ [1, 2, 3], [4, 5, 6] ]) print(values.flatten(order="C")) print(values.flatten(order="F"))

Expected output:

[1 2 3 4 5 6] [1 4 2 5 3 6]
Order Element sequence Meaning
'C' 1, 2, 3, 4, 5, 6 Read across rows.
'F' 1, 4, 2, 5, 3, 6 Read down columns.

The order argument describes how elements are indexed and read for the operation. It does not necessarily mean that the underlying memory is physically stored in that order.

11. Common Reshape Errors

A reshape operation fails when the requested dimensions cannot accommodate the original number of elements.

import numpy as np values = np.array([1, 2, 3, 4, 5, 6]) # Valid: six elements can fit into two rows and three columns. valid = values.reshape(2, 3) # Invalid: six elements cannot fit into a 4-by-2 array. # invalid = values.reshape(4, 2) print(valid)

How to Prevent Errors

  • Check the original array's size.
  • Calculate the product of the requested dimensions.
  • Use -1 when one dimension should be inferred.
  • Check the resulting shape before further processing.
Rule: For a valid reshape, the product of the requested dimensions must equal the original number of elements.

12. Practical Activity

Activity: Reshape Student Marks

Samadhan, Pradnya, and Samiksha are analyzing twelve marks stored in a one-dimensional array. Arrange the marks into a three-by-four matrix, then convert the matrix back into a one-dimensional array.

Tasks:

  1. Create an array containing twelve integer marks.
  2. Reshape the array into three rows and four columns.
  3. Print the reshaped array and its shape.
  4. Flatten the array using flatten().
  5. Use ravel() and compare the output.

Sample Solution

import numpy as np marks = np.array([ 78, 85, 90, 82, 88, 76, 92, 80, 91, 87, 84, 95 ]) matrix = marks.reshape(3, 4) print("Reshaped marks:") print(matrix) print("Shape:", matrix.shape) flat_copy = matrix.flatten() flat_result = matrix.ravel() print("Flattened:", flat_copy) print("Ravel:", flat_result)

Expected key results:

  • Reshaped array shape: (3, 4)
  • Total elements: 12
  • Flattened shape: (12,)
  • Both flattening methods produce the same values in the default order.

Summary

  • reshape() changes an array's dimensions without changing its element count.
  • Every requested shape must be compatible with the original size.
  • -1 allows NumPy to infer one dimension automatically.
  • flatten() creates an independent one-dimensional copy.
  • ravel() returns a one-dimensional array and may return a view when possible.
  • The 'C' and 'F' orders determine how elements are indexed during the operation.

Reshaping and flattening help organize array data for mathematical operations, analysis, and machine learning workflows.