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

First NumPy Program

Write your first NumPy program, create numerical arrays, perform calculations, and understand how Python displays the results of array operations.

1. Learning Objectives

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

  • Import NumPy into a Python program.
  • Create a NumPy array using np.array().
  • Display array values using print().
  • Perform basic arithmetic on numerical arrays.
  • Calculate totals and averages using NumPy functions.
  • Understand common errors in beginner NumPy programs.
  • Write and execute a complete NumPy practice program.

2. Preparing Your First Program

Before writing your first NumPy program, confirm that NumPy is installed in the Python environment selected by your IDE. Create a Python file named main.py in your project.

Step 1: Import NumPy

import numpy as np

This statement imports the NumPy library and assigns it the commonly used alias np.

Step 2: Create an Array

numbers = np.array([10, 20, 30, 40, 50])

The np.array() function converts the supplied sequence of values into a NumPy array.

Step 3: Display the Array

print(numbers)

Output:

[10 20 30 40 50]
Tip: Python statements execute in order. Import NumPy before using its functions, and create a variable before trying to display its value.

3. Understanding the Program Structure

1. Import the NumPy Library 2. Create Numerical Data 3. Perform Calculations 4. Display the Results
Figure 1: A typical sequence for a beginner NumPy program.
Statement Purpose
import numpy as np Makes NumPy available through the alias np.
np.array([...]) Creates an array from the supplied values.
np.sum(array) Calculates the sum of the array elements.
np.mean(array) Calculates the arithmetic mean of the array elements.
print() Displays values in the program output.

4. Program Example: Student Marks Analysis

At CIIT TRANING INSTITUTE, Samadhan wants to calculate the total and average marks of five students. NumPy can perform these calculations directly on an array.

Complete Program

import numpy as np

marks = np.array([78, 85, 92, 67, 88])

total_marks = np.sum(marks)
average_marks = np.mean(marks)
highest_marks = np.max(marks)
lowest_marks = np.min(marks)

print("Student Marks:", marks)
print("Total Marks:", total_marks)
print("Average Marks:", average_marks)
print("Highest Marks:", highest_marks)
print("Lowest Marks:", lowest_marks)

Output:

Student Marks: [78 85 92 67 88]
Total Marks: 410
Average Marks: 82.0
Highest Marks: 92
Lowest Marks: 67

Step-by-Step Explanation

  1. marks stores the five marks in a NumPy array.
  2. np.sum(marks) adds all the marks.
  3. np.mean(marks) calculates the average.
  4. np.max(marks) returns the highest value.
  5. np.min(marks) returns the lowest value.
  6. The print() statements display the calculated results.
Classroom connection: Pradnya can use the same approach to analyze a different set of marks without writing a separate addition or comparison statement for each student.

5. Performing Arithmetic Operations

NumPy supports element-wise arithmetic. When an arithmetic operation is applied to an array and a scalar, the operation is applied to every element.

Example: Basic Calculations

import numpy as np

numbers = np.array([10, 20, 30])

print("Original:", numbers)
print("Addition:", numbers + 5)
print("Subtraction:", numbers - 5)
print("Multiplication:", numbers * 2)
print("Division:", numbers / 10)

Output:

Original: [10 20 30]
Addition: [15 25 35]
Subtraction: [ 5 15 25]
Multiplication: [20 40 60]
Division: [1. 2. 3.]
Operator Operation Example Result
+ Adds a value to each element. [15, 25, 35]
- Subtracts a value from each element. [5, 15, 25]
* Multiplies each element by a value. [20, 40, 60]
/ Divides each element by a value. [1.0, 2.0, 3.0]
Remember: Division of numerical NumPy arrays can produce floating-point values. Avoid dividing by zero unless you have deliberately handled the resulting behavior.

6. Program Example: Sales Calculation

Samiksha is analyzing daily sales at a practice store. She wants to calculate total sales, average sales, and the highest daily sales value.

Complete Program

import numpy as np

sales = np.array([1200, 1500, 1800, 1350, 2150])

total_sales = np.sum(sales)
average_sales = np.mean(sales)
highest_sales = np.max(sales)

print("Daily Sales:", sales)
print("Total Sales:", total_sales)
print("Average Sales:", average_sales)
print("Highest Sales:", highest_sales)

Output:

Daily Sales: [1200 1500 1800 1350 2150]
Total Sales: 8000
Average Sales: 1600.0
Highest Sales: 2150

This program illustrates how one array can represent a set of daily sales values and how NumPy functions can summarize those values.

7. Understanding Array Attributes

NumPy arrays provide attributes that describe their structure. These attributes are useful when inspecting data before performing more complex operations.

import numpy as np

numbers = np.array([10, 20, 30, 40])

print("Array:", numbers)
print("Number of dimensions:", numbers.ndim)
print("Shape:", numbers.shape)
print("Number of elements:", numbers.size)
print("Data type:", numbers.dtype)

Example output:

Array: [10 20 30 40]
Number of dimensions: 1
Shape: (4,)
Number of elements: 4
Data type: int64

The exact integer data type can vary by platform and how the array is created. Read the value displayed by your own program rather than assuming a particular type.

Attribute Meaning
ndim Number of dimensions in the array.
shape Length along each dimension.
size Total number of elements.
dtype Data type used to represent array elements.

8. Common Beginner Mistakes

Mistake 1: Forgetting to Import NumPy

Calling np.array() before importing NumPy causes a name-related error.

Mistake 2: Misspelling a Function

NumPy function names must be spelled correctly. For example, use np.mean() to calculate an average.

Mistake 3: Using an Incorrect Variable Name

Python variable names are case-sensitive. marks and Marks are different names.

Mistake 4: Running the Wrong Interpreter

If the IDE selects an environment without NumPy, the import statement may fail. Check the active interpreter and package installation.

Mistake 5: Miscalculating Expected Results

Always verify that the expected output matches the supplied input values. A correct program cannot produce a total that does not match the sum of its elements.

9. Classroom Practical Activity

Activity: Analyze Student Performance

Samadhan, Pradnya, and Samiksha are learning how to analyze numerical data. Complete the following activity using a NumPy array.

  1. Create an array containing the marks 76, 89, 94, 68, and 83.
  2. Display the complete array.
  3. Calculate the total marks.
  4. Calculate the average marks.
  5. Find the highest and lowest marks.
  6. Add five bonus marks to each array element.
  7. Display the updated array.

Starter Program

import numpy as np

marks = np.array([76, 89, 94, 68, 83])

print("Original Marks:", marks)
print("Total:", np.sum(marks))
print("Average:", np.mean(marks))
print("Highest:", np.max(marks))
print("Lowest:", np.min(marks))

updated_marks = marks + 5
print("Updated Marks:", updated_marks)

Run the program and compare the output with your own calculations. In a real assessment, apply any bonus marks according to the instructor's stated rules.

Practice Questions

  1. Which statement imports NumPy using the alias np?
  2. What does np.array() do?
  3. Which function calculates the sum of an array?
  4. Which function calculates the average of an array?
  5. How can you multiply every array element by two?
  6. What information does the shape attribute provide?
  7. Why should you verify the selected Python interpreter?

Summary

In this lesson, you wrote your first NumPy program, imported the library, created numerical arrays, and displayed their contents.

You also practiced arithmetic operations, calculated totals and averages, inspected array attributes, and explored student marks and sales analysis examples.