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

Vectors and Matrices

Learn how to represent vectors and matrices using NumPy arrays. Understand vector dimensions, matrix rows and columns, matrix properties, vector operations, and basic linear algebra concepts through practical examples and numerical datasets.

1. Learning Objectives

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

  • Understand vectors and matrices in numerical computing.
  • Create one-dimensional and two-dimensional NumPy arrays.
  • Identify vector and matrix dimensions.
  • Access individual elements using indexing.
  • Perform basic vector arithmetic.
  • Understand matrix rows, columns, shape, and size.
  • Calculate vector magnitude and distance.
  • Understand the difference between element-wise multiplication and matrix multiplication.
  • Use vectors and matrices in practical data analysis problems.

2. Introduction to Vectors and Matrices

Vectors and matrices are fundamental concepts in linear algebra. They are widely used in data science, machine learning, engineering, statistics, computer graphics, and scientific computing.

A vector is an ordered collection of numerical values. A matrix is a rectangular arrangement of values organized into rows and columns.

Vector Example

A vector containing three values can be represented as:

[10, 20, 30]

This vector contains three elements and can be represented using a one-dimensional NumPy array.

Matrix Example

A matrix containing two rows and three columns is:

[[10, 20, 30], [40, 50, 60]]

This matrix contains six elements arranged in two rows and three columns.

Key Concept: NumPy represents both vectors and matrices using the ndarray data structure. A vector commonly uses one dimension, while a matrix uses two dimensions.

3. Creating a Vector in NumPy

A one-dimensional NumPy array can represent a vector. Use np.array() to create a vector from a Python list.

import numpy as np vector = np.array([10, 20, 30, 40, 50]) print(vector) print("Dimensions:", vector.ndim) print("Shape:", vector.shape) print("Size:", vector.size)

Output:

[10 20 30 40 50] Dimensions: 1 Shape: (5,) Size: 5

The vector has one dimension, a shape of (5,), and five elements.

One-Dimensional Vector 10 20 30 40 50 Five elements arranged in one dimension

A one-dimensional vector stores values in a single sequence.

4. Creating a Matrix in NumPy

A two-dimensional NumPy array can represent a matrix. Each inner list represents one row, and each value within that row occupies a column.

import numpy as np matrix = np.array([ [10, 20, 30], [40, 50, 60] ]) print(matrix) print("Dimensions:", matrix.ndim) print("Shape:", matrix.shape) print("Size:", matrix.size)

Output:

[[10 20 30] [40 50 60]] Dimensions: 2 Shape: (2, 3) Size: 6

The matrix has two dimensions, two rows, three columns, and six total elements.

Remember: A matrix with shape (2, 3) contains two rows and three columns. The shape is reported in the order (rows, columns).

5. Understanding Matrix Rows and Columns

Rows and columns help organize matrix data. For example, a student marks matrix can store one student per row and one subject per column.

import numpy as np marks = np.array([ [85, 90, 78], [72, 88, 91], [95, 82, 89] ]) print("Marks matrix:") print(marks) print("First row:", marks[0]) print("Second row:", marks[1]) print("First column:", marks[:, 0]) print("Second column:", marks[:, 1])

Output:

Marks matrix: [[85 90 78] [72 88 91] [95 82 89]] First row: [85 90 78] Second row: [72 88 91] First column: [85 72 95] Second column: [90 88 82]

NumPy uses zero-based indexing, so the first row has index 0 and the first column has index 0.

Reading Matrix Indexing

Expression Meaning
marks[0] Selects the first row.
marks[1] Selects the second row.
marks[:, 0] Selects the first column.
marks[:, 1] Selects the second column.
marks[1, 2] Selects the value in the second row and third column.

6. Accessing Vector Elements

Vector elements can be accessed using their index. NumPy starts indexing at zero.

import numpy as np vector = np.array([10, 20, 30, 40, 50]) print("First element:", vector[0]) print("Third element:", vector[2]) print("Last element:", vector[-1])

Output:

First element: 10 Third element: 30 Last element: 50

Positive indexing starts at zero, while negative indexing counts backward from the end of the array.

7. Basic Vector Arithmetic

NumPy supports arithmetic operations on vectors. When two vectors have compatible shapes, arithmetic operations such as addition, subtraction, and element-wise multiplication can be performed.

import numpy as np a = np.array([10, 20, 30]) b = np.array([1, 2, 3]) print("Addition:", a + b) print("Subtraction:", a - b) print("Multiplication:", a * b) print("Division:", a / b)

Output:

Addition: [11 22 33] Subtraction: [ 9 18 27] Multiplication: [10 40 90] Division: [10. 10. 10.]

These operations are element-wise. Each element in the first vector is combined with the corresponding element in the second vector.

Important: The * operator performs element-wise multiplication for NumPy arrays. It does not perform matrix multiplication.

8. Scalar Operations on Vectors

A scalar is a single numerical value. NumPy allows a scalar to be applied to every element of a vector.

import numpy as np vector = np.array([10, 20, 30, 40]) print("Add 5:", vector + 5) print("Multiply by 2:", vector * 2) print("Subtract 3:", vector - 3) print("Divide by 10:", vector / 10)

Output:

Add 5: [15 25 35 45] Multiply by 2: [20 40 60 80] Subtract 3: [ 7 17 27 37] Divide by 10: [1. 2. 3. 4.]

The scalar is applied to each element without requiring an explicit Python loop.

9. Vector Magnitude

The magnitude, or Euclidean norm, measures the length of a vector. For a vector with components [x, y], its magnitude is:

Magnitude = square root of the sum of squared components.

For a vector with components [3, 4], the magnitude is 5.

import numpy as np vector = np.array([3, 4]) magnitude = np.linalg.norm(vector) print("Vector:", vector) print("Magnitude:", magnitude)

Output:

Vector: [3 4] Magnitude: 5.0

NumPy's np.linalg.norm() calculates the Euclidean norm by default for a one-dimensional vector.

Magnitude of a Three-Dimensional Vector

import numpy as np vector = np.array([2, 3, 6]) print(np.linalg.norm(vector))

Output:

7.0

The magnitude is 7 because the sum of the squared components is 49, whose square root is 7.

10. Calculating Distance Between Vectors

The Euclidean distance between two vectors is the magnitude of their difference. It measures how far apart the two vectors are in numerical space.

import numpy as np point_a = np.array([1, 2]) point_b = np.array([4, 6]) difference = point_b - point_a distance = np.linalg.norm(difference) print("Difference:", difference) print("Distance:", distance)

Output:

Difference: [3 4] Distance: 5.0

This technique is useful in geometry, clustering, machine learning, and numerical comparisons.

11. Matrix Arithmetic

Matrices of compatible shapes can be added and subtracted element by element. Scalar operations can also be applied to every matrix element.

import numpy as np a = np.array([ [1, 2], [3, 4] ]) b = np.array([ [5, 6], [7, 8] ]) print("Addition:") print(a + b) print("Subtraction:") print(a - b) print("Scalar multiplication:") print(a * 2)

Output:

Addition: [[ 6 8] [10 12]] Subtraction: [[-4 -4] [-4 -4]] Scalar multiplication: [[2 4] [6 8]]

Addition and subtraction require compatible shapes. In this example, both matrices have shape (2, 2).

12. Element-Wise Multiplication vs Matrix Multiplication

NumPy supports two different multiplication concepts. Element-wise multiplication multiplies corresponding elements, while matrix multiplication combines rows and columns according to linear algebra rules.

Element-Wise Multiplication

import numpy as np a = np.array([ [1, 2], [3, 4] ]) b = np.array([ [5, 6], [7, 8] ]) print(a * b)

Output:

[[ 5 12] [21 32]]

Matrix Multiplication

import numpy as np a = np.array([ [1, 2], [3, 4] ]) b = np.array([ [5, 6], [7, 8] ]) print(a @ b)

Output:

[[19 22] [43 50]]

The @ operator performs matrix multiplication. The np.matmul() function can also be used.

Remember: Use * for element-wise multiplication and @ for matrix multiplication.

13. Matrix Transpose

The transpose of a matrix exchanges its rows and columns. For a two-dimensional NumPy array, use the .T attribute.

import numpy as np matrix = np.array([ [10, 20, 30], [40, 50, 60] ]) print("Original matrix:") print(matrix) print("Transposed matrix:") print(matrix.T) print("Original shape:", matrix.shape) print("Transposed shape:", matrix.T.shape)

Output:

Original matrix: [[10 20 30] [40 50 60]] Transposed matrix: [[10 40] [20 50] [30 60]] Original shape: (2, 3) Transposed shape: (3, 2)

The original matrix has two rows and three columns. Its transpose has three rows and two columns.

14. Identity and Zero Matrices

NumPy provides convenient functions to create matrices with common mathematical structures.

import numpy as np zero_matrix = np.zeros((3, 3)) identity_matrix = np.eye(3) ones_matrix = np.ones((2, 3)) print("Zero matrix:") print(zero_matrix) print("Identity matrix:") print(identity_matrix) print("Ones matrix:") print(ones_matrix)

np.zeros() creates an array filled with zeros. np.eye() creates an identity matrix, and np.ones() creates an array filled with ones.

Identity Matrix

An identity matrix contains ones along its main diagonal and zeros elsewhere. For compatible matrices, multiplying by the identity matrix leaves the matrix unchanged.

15. Practical Activity: Student Marks Matrix

Activity Description

Samadhan, Pradnya, and Samiksha are analyzing marks at CIIT TRANING INSTITUTE. Each student has marks for Python, NumPy, and Statistics.

Complete the following tasks:

  1. Create a two-dimensional array containing the marks.
  2. Display the matrix shape and dimensions.
  3. Calculate each student's total marks.
  4. Calculate each student's average marks.
  5. Calculate the average marks for each subject.
  6. Find the highest mark in the matrix.
  7. Transpose the marks matrix.

Sample Solution

import numpy as np students = np.array([ "Samadhan", "Pradnya", "Samiksha" ]) subjects = np.array([ "Python", "NumPy", "Statistics" ]) marks = np.array([ [85, 90, 78], [72, 88, 91], [95, 82, 89] ]) print("Students:", students) print("Subjects:", subjects) print("Marks matrix:") print(marks) print("Shape:", marks.shape) print("Dimensions:", marks.ndim) print("Student totals:", marks.sum(axis=1)) print("Student averages:", marks.mean(axis=1)) print("Subject averages:", marks.mean(axis=0)) print("Highest mark:", marks.max()) print("Transposed matrix:") print(marks.T)

This activity demonstrates how NumPy matrices can organize structured numerical data and support calculations across rows and columns.

16. Common Mistakes and Best Practices

Common Mistakes

  • Confusing a one-dimensional vector with a two-dimensional column matrix.
  • Forgetting that NumPy indexing starts at zero.
  • Confusing rows with columns when reading a matrix shape.
  • Using * when matrix multiplication is required.
  • Trying to add matrices with incompatible shapes.
  • Assuming shape, size, and ndim mean the same thing.

Best Practices

  • Use np.array() to create vectors and matrices.
  • Check shape and ndim when working with arrays.
  • Use axis=0 for column-wise aggregation on a two-dimensional array.
  • Use axis=1 for row-wise aggregation on a two-dimensional array.
  • Use @ or np.matmul() for matrix multiplication.
  • Use np.linalg.norm() for vector magnitude and Euclidean distance.

17. Practice Exercises

  1. Create a vector containing ten integers and display its shape, size, and number of dimensions.
  2. Create a 3 × 3 matrix and display its first row and last column.
  3. Add and subtract two vectors of equal length.
  4. Multiply a vector by a scalar and explain the result.
  5. Calculate the magnitude of the vector [6, 8].
  6. Calculate the Euclidean distance between [1, 2] and [4, 6].
  7. Create two 2 × 2 matrices and compare element-wise multiplication with matrix multiplication.
  8. Transpose a 2 × 3 matrix and display the new shape.
  9. Create an identity matrix of order four.
  10. Create a student marks matrix for Samadhan, Pradnya, and Samiksha and calculate row and column averages.

Summary

In this lesson, we learned how to represent vectors and matrices using NumPy arrays. We explored one-dimensional and two-dimensional arrays, indexing, matrix rows and columns, array shapes, and dimensions.

We performed vector and matrix arithmetic, distinguished element-wise multiplication from matrix multiplication, calculated vector magnitudes and distances, transposed matrices, and created identity, zero, and ones matrices.

Remember to check array shapes before performing operations, use the appropriate multiplication operator, and understand whether a calculation should operate across rows or columns. These concepts provide the foundation for more advanced NumPy linear algebra.