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

Array Shape, Size and Dimensions

Learn how to inspect the structure of NumPy arrays using shape, size, and ndim. Understand rows, columns, dimensions, and the relationship between an array's structure and its total elements.

1. Learning Objectives

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

  • Understand the structure of a NumPy array.
  • Inspect array dimensions using the ndim attribute.
  • Use shape to identify the length of each dimension.
  • Use size to count the total number of elements.
  • Distinguish between shape, size, and dimensions.
  • Inspect one-dimensional, two-dimensional, and three-dimensional arrays.
  • Calculate the total number of elements from an array's shape.
  • Use array attributes to validate datasets.
  • Recognize common shape-related errors.
  • Apply array inspection to practical data analysis.
Beginner tip: Remember these three attributes: shape tells you the dimensions' lengths, size counts all elements, and ndim tells you the number of dimensions.

2. Understanding Array Shape

The shape of a NumPy array describes how many elements exist along each dimension. NumPy returns the shape as a tuple.

For a one-dimensional array, the shape contains one number. For a two-dimensional array, it contains the number of rows followed by the number of columns.

Example: Inspecting Array Shape

import numpy as np numbers = np.array([10, 20, 30, 40, 50]) print(numbers.shape) # Output: (5,) marks = np.array([ [78, 85, 90], [82, 79, 94] ]) print(marks.shape) # Output: (2, 3)

The one-dimensional array has five elements. The two-dimensional array contains two rows and three columns.

Understanding Array Shape One-dimensional array: shape = (5,) 10 20 30 40 50 Two-dimensional array: shape = (2, 3) 78 85 90 82 79 94
Figure 1: The shape tuple describes the length of each dimension.
Remember: For a two-dimensional array, (2, 3) means two rows and three columns.

3. Understanding Array Dimensions with ndim

The ndim attribute returns the number of dimensions in a NumPy array. It does not return the number of elements or the length of a particular dimension.

import numpy as np one_d = np.array([10, 20, 30]) two_d = np.array([ [10, 20, 30], [40, 50, 60] ]) three_d = np.array([ [[1, 2], [3, 4]], [[5, 6], [7, 8]] ]) print(one_d.ndim) # Output: 1 print(two_d.ndim) # Output: 2 print(three_d.ndim) # Output: 3

Common Array Dimensions

Array Type Example Shape ndim
One-dimensional array (3,) 1
Two-dimensional array (2, 3) 2
Three-dimensional array (2, 2, 2) 3
Practical use: Use ndim when you need to verify whether an array is one-dimensional, two-dimensional, or higher-dimensional before processing it.

4. Understanding Array Size

The size attribute returns the total number of elements in an array, regardless of how many dimensions it has.

import numpy as np numbers = np.array([10, 20, 30, 40]) print(numbers.size) # Output: 4 marks = np.array([ [78, 85, 90], [82, 79, 94] ]) print(marks.size) # Output: 6

The two-dimensional array has two rows and three columns. Therefore, its total number of elements is six.

Calculating Size from Shape

For an array with shape (2, 3), the total number of elements is calculated by multiplying the lengths of the dimensions.

shape = (2, 3) total_elements = shape[0] * shape[1] print(total_elements) # Output: 6

For higher-dimensional arrays, multiply the lengths of all dimensions to calculate the total number of elements.

Important: Do not confuse size with ndim. An array can contain many elements while having only one dimension.

5. Difference Between Shape, Size, and Dimensions

These three attributes describe different properties of the same array. Understanding the difference helps prevent mistakes while working with datasets.

Attribute Meaning Example Result
shape Length of each dimension. (2, 3)
size Total number of elements. 6
ndim Number of dimensions. 2
import numpy as np data = np.array([ [10, 20, 30], [40, 50, 60] ]) print("Shape:", data.shape) print("Size:", data.size) print("Dimensions:", data.ndim)

Output

Shape: (2, 3) Size: 6 Dimensions: 2
Quick memory trick: Shape = arrangement, Size = total elements, ndim = number of dimensions.

6. Inspecting Three-Dimensional Arrays

A three-dimensional array contains elements organized across three dimensions. It can be understood as a collection of two-dimensional arrays.

import numpy as np data = np.array([ [[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]] ]) print(data.shape) # Output: (2, 2, 3) print(data.size) # Output: 12 print(data.ndim) # Output: 3
Three-Dimensional Array Matrix 0 Matrix 1 1 2 3 4 5 6 7 8 9 10 11 12 Shape: (2, 2, 3) 2 matrices × 2 rows × 3 columns = 12 elements
Figure 2: The array contains two matrices, each with two rows and three columns.
Remember: A shape of (2, 2, 3) means there are two groups, each containing two rows and three columns.

7. Empty Arrays and Single-Element Arrays

NumPy can represent arrays containing no elements, arrays with one element, and arrays with multiple dimensions. Their shapes and sizes help explain their structures.

import numpy as np empty_array = np.array([]) single_value = np.array([25]) single_element_2d = np.array([[25]]) print(empty_array.shape, empty_array.size, empty_array.ndim) # Output: (0,) 0 1 print(single_value.shape, single_value.size, single_value.ndim) # Output: (1,) 1 1 print(single_element_2d.shape, single_element_2d.size, single_element_2d.ndim) # Output: (1, 1) 1 2
Array Shape Size ndim
np.array([]) (0,) 0 1
np.array([25]) (1,) 1 1
np.array([[25]]) (1, 1) 1 2
Practical use: Empty and single-element arrays can occur while preparing datasets, filtering values, or processing the result of a calculation.

8. Using Shape to Validate Data

Before combining or processing arrays, it is useful to inspect their shapes. This helps identify missing rows, unexpected columns, and incompatible structures.

import numpy as np student_marks = np.array([ [78, 85, 90], [82, 79, 94], [75, 88, 84] ]) print("Shape:", student_marks.shape) rows, columns = student_marks.shape print("Number of students:", rows) print("Subjects per student:", columns) if columns == 3: print("The dataset contains three subject columns.")

Example Output

Shape: (3, 3) Number of students: 3 Subjects per student: 3 The dataset contains three subject columns.
Important: Unpacking rows, columns = array.shape works for a two-dimensional array because its shape contains two values. For arrays with other numbers of dimensions, inspect the shape before unpacking it.

9. Shape and Size in Practical Calculations

Array attributes are useful for checking whether a dataset contains the expected number of values and for understanding how its elements are arranged.

Example: Monthly Sales Data

Samiksha is analyzing monthly sales for four products across three months. She wants to inspect the dataset before calculating totals.

import numpy as np sales = np.array([ [120, 150, 180], [200, 220, 250], [175, 190, 210], [300, 320, 350] ]) print("Shape:", sales.shape) print("Size:", sales.size) print("Dimensions:", sales.ndim) monthly_totals = sales.sum(axis=0) print("Monthly totals:", monthly_totals)

Expected Output

Shape: (4, 3) Size: 12 Dimensions: 2 Monthly totals: [795 880 990]

The shape indicates four products and three monthly values per product. The size confirms that the array contains twelve values in total.

10. Common Shape and Dimension Errors

Problem Reason Solution
Confusing shape and size Shape describes each dimension, while size counts elements. Inspect both attributes separately.
Unexpected number of dimensions The input data may be nested differently than expected. Check ndim and shape.
Incorrect shape unpacking The array has more or fewer dimensions than expected. Check the shape before unpacking it.
Incorrect number of elements The dataset may contain missing or additional values. Inspect size and the input data.
Unexpected matrix structure Rows may contain different numbers of values in the source data. Validate the input structure before creating the array.
Debugging tip: Print the array's shape, size, and dimensions immediately after creating or loading a dataset.
print(sales.shape) print(sales.size) print(sales.ndim)

11. Practical Activity: Student Dataset Inspection

Activity: Inspect Student Marks

Pradnya is checking a marks dataset before performing calculations. Use NumPy attributes to determine the number of students, the number of subjects, and the total number of recorded marks.

import numpy as np marks = np.array([ [78, 85, 90, 88], [82, 79, 94, 91], [75, 88, 84, 86] ]) print("Shape:", marks.shape) print("Size:", marks.size) print("Dimensions:", marks.ndim) students, subjects = marks.shape print("Students:", students) print("Subjects:", subjects) print("Average mark:", marks.mean())

Expected Output

Shape: (3, 4) Size: 12 Dimensions: 2 Students: 3 Subjects: 4 Average mark: 85.0

This activity demonstrates how shape, size, and dimensions help verify the structure of a dataset before analysis.

12. Practice Exercises

Use the following arrays to complete the exercises:

import numpy as np numbers = np.array([10, 20, 30, 40, 50]) marks = np.array([ [78, 85, 90], [82, 79, 94] ]) data_3d = np.array([ [[1, 2], [3, 4]], [[5, 6], [7, 8]] ])
  1. Print the shape of the numbers array.
  2. Print the size of the marks array.
  3. Print the number of dimensions of the marks array.
  4. Find the shape and size of the three-dimensional array.
  5. Calculate the total elements in an array with shape (3, 4).
  6. Explain the difference between shape and ndim.
  7. Print the number of rows and columns in the marks array.
  8. Create an array containing one element and inspect its attributes.

Challenge Exercise

Samadhan is preparing a sales dataset for five products across four months. Create a two-dimensional NumPy array and complete the following tasks:

  • Display the array's shape, size, and dimensions.
  • Calculate the number of products and monthly values.
  • Verify that the array contains twenty elements.
  • Calculate the total sales for each month.
  • Explain how shape helps verify the dataset structure.
Practice goal: Try to determine the expected shape, size, and number of dimensions before running each program.

Summary

In this lesson, we learned how NumPy describes array structure using the shape, size, and ndim attributes. We inspected one-dimensional, two-dimensional, and three-dimensional arrays. We also learned how shape represents the length of each dimension and how size gives the total number of elements.

Finally, we used array attributes to validate datasets, inspect student marks, analyze sales records, and identify common shape-related errors. These attributes are essential when preparing, validating, reshaping, and analyzing NumPy arrays.