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

NumPy Beginner Practice and Exercises

This lesson provides hands-on exercises for beginners learning NumPy. You will practice creating arrays, accessing elements, slicing arrays, checking attributes, performing arithmetic operations, calculating statistics, applying conditions, and reshaping arrays. Each exercise includes a task, expected output, and solution so that you can practice independently and verify your understanding.

1. Learning Objectives

After completing this practice lesson, you will be able to:

  • Create one-dimensional and multidimensional NumPy arrays.
  • Use array indexing and slicing.
  • Inspect array shape, size, dimensions, and data type.
  • Perform arithmetic operations on arrays.
  • Calculate sum, mean, minimum, and maximum.
  • Filter values using Boolean conditions.
  • Reshape arrays and generate sequences.
  • Write and test basic NumPy programs independently.

2. Exercise 1: Create a NumPy Array

Task: Create a NumPy array containing the numbers 10, 20, 30, 40, and 50. Display the array and its data type.

import numpy as np numbers = np.array([10, 20, 30, 40, 50]) print(numbers) print(numbers.dtype)

Expected Output

[10 20 30 40 50] int64

The displayed integer data type may differ by platform. NumPy commonly uses int64 on 64-bit systems for this example, but the exact default integer type is environment-dependent.

Learning point: np.array() converts a Python sequence into a NumPy array.

3. Exercise 2: Create Arrays Using arange()

Task: Generate the integers from 1 through 10 using np.arange().

numbers = np.arange(1, 11) print(numbers)

Expected Output

[ 1 2 3 4 5 6 7 8 9 10]

The stop value is exclusive. Therefore, np.arange(1, 11) includes 1 through 10 but excludes 11.

4. Exercise 3: Create Zeros and Ones Arrays

Task: Create an array containing four zeros and another array containing five ones.

zeros_array = np.zeros(4) ones_array = np.ones(5) print("Zeros:", zeros_array) print("Ones:", ones_array)

Expected Output

Zeros: [0. 0. 0. 0.] Ones: [1. 1. 1. 1. 1.]

By default, these functions produce floating-point arrays. Use the dtype argument if you need integer values.

zeros_array = np.zeros(4, dtype=int) ones_array = np.ones(5, dtype=int) print(zeros_array) print(ones_array)

5. Exercise 4: Access Array Elements

Task: Given an array, display the first element, third element, and last element.

marks = np.array([65, 78, 82, 91, 74]) print("First:", marks[0]) print("Third:", marks[2]) print("Last:", marks[-1])

Expected Output

First: 65 Third: 82 Last: 74
Remember: Python indexing starts at 0. Negative index -1 accesses the last element.

6. Exercise 5: Slice an Array

Task: Display the first three elements, the elements from index 1 through index 3, and the last two elements.

numbers = np.array([10, 20, 30, 40, 50, 60]) print(numbers[:3]) print(numbers[1:4]) print(numbers[-2:])

Expected Output

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

In a slice, the starting index is included and the stopping index is excluded.

7. Exercise 6: Check Array Attributes

Task: Create a two-dimensional array and display its shape, number of dimensions, and total number of elements.

matrix = np.array([ [1, 2, 3], [4, 5, 6] ]) print("Shape:", matrix.shape) print("Dimensions:", matrix.ndim) print("Size:", matrix.size)

Expected Output

Shape: (2, 3) Dimensions: 2 Size: 6
Attribute Meaning
shape Number of elements along each dimension.
ndim Number of dimensions.
size Total number of elements.
dtype Data type of the array elements.

8. Exercise 7: Perform Arithmetic Operations

Task: Add, subtract, multiply, and divide two arrays element by element.

a = np.array([10, 20, 30]) b = np.array([2, 4, 5]) print("Addition:", a + b) print("Subtraction:", a - b) print("Multiplication:", a * b) print("Division:", a / b)

Expected Output

Addition: [12 24 35] Subtraction: [ 8 16 25] Multiplication: [ 20 80 150] Division: [ 5. 5. 6.]

NumPy performs these operations element by element when the arrays have compatible shapes.

9. Exercise 8: Calculate Sum and Average

Task: Calculate the sum, mean, minimum, and maximum of a marks array.

marks = np.array([70, 85, 90, 65, 80]) print("Sum:", np.sum(marks)) print("Mean:", np.mean(marks)) print("Minimum:", np.min(marks)) print("Maximum:", np.max(marks))

Expected Output

Sum: 390 Mean: 78.0 Minimum: 65 Maximum: 90
Practical use: These functions are useful for analyzing marks, sales figures, measurements, and other numerical datasets.

10. Exercise 9: Filter Values Using Conditions

Task: Select all values greater than 50 from the array.

numbers = np.array([15, 60, 35, 80, 45, 90]) filtered = numbers[numbers > 50] print(filtered)

Expected Output

[60 80 90]

The condition numbers > 50 creates a Boolean array. Boolean indexing returns the values where the condition is True.

11. Exercise 10: Use Multiple Conditions

Task: Select values that are greater than or equal to 30 and less than or equal to 70.

numbers = np.array([10, 30, 45, 60, 75, 90]) filtered = numbers[ (numbers >= 30) & (numbers <= 70) ] print(filtered)

Expected Output

[30 45 60]
Important: Put each comparison inside parentheses when combining NumPy conditions with & or |. Use these operators instead of Python's and and or for element-wise array conditions.

12. Exercise 11: Reshape an Array

Task: Create an array of 12 integers and reshape it into three rows and four columns.

numbers = np.arange(1, 13) matrix = numbers.reshape(3, 4) print(matrix) print("Shape:", matrix.shape)

Expected Output

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

The total number of elements must remain unchanged. Here, 12 elements are reshaped into a matrix with 3 rows and 4 columns.

13. Exercise 12: Calculate Row and Column Totals

Task: Calculate the sum of each row and each column in a matrix.

sales = np.array([ [100, 200, 300], [150, 250, 350], [120, 220, 320] ]) row_totals = np.sum(sales, axis=1) column_totals = np.sum(sales, axis=0) print("Row totals:", row_totals) print("Column totals:", column_totals)

Expected Output

Row totals: [600 750 660] Column totals: [370 670 970]

axis=1 calculates one result for each row. axis=0 calculates one result for each column.

14. Exercise 13: Generate Evenly Spaced Values

Task: Generate five evenly spaced values between 0 and 10, including both endpoints.

values = np.linspace(0, 10, 5) print(values)

Expected Output

[ 0. 2.5 5. 7.5 10. ]

Unlike np.arange(), which uses a step size, np.linspace() lets you specify the number of values to generate.

15. Exercise 14: Find Unique Values

Task: Find the unique values in an array that contains duplicates.

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

Expected Output

[10 20 30 40]

np.unique() returns the distinct values in sorted order for this one-dimensional numeric array.

16. Exercise 15: Replace Values Using np.where()

Task: Replace marks greater than or equal to 40 with "Pass" and all other marks with "Fail".

marks = np.array([75, 32, 48, 25, 90]) status = np.where( marks >= 40, "Pass", "Fail" ) print(status)

Expected Output

['Pass' 'Fail' 'Pass' 'Fail' 'Pass']

np.where() selects values according to a condition. It is useful for applying simple classifications to numerical arrays.

17. Mini Project: Student Marks Analysis

Combine your knowledge of arrays, aggregation, and conditions to analyze marks for three students.

Project Requirements

  • Store student names and marks in arrays.
  • Calculate each student's average marks.
  • Find the highest average.
  • Identify students with averages of at least 75.
  • Display the final results.

Solution

students = np.array([ "Samadhan", "Pradnya", "Samiksha" ]) marks = np.array([ [80, 85, 90], [70, 75, 80], [60, 65, 70] ]) averages = np.mean(marks, axis=1) print("Student averages:") print(averages) top_index = np.argmax(averages) print("Highest average:", averages[top_index]) print("Top student:", students[top_index]) qualified = students[averages >= 75] print("Students with average >= 75:") print(qualified)

Expected Output

Student averages: [85. 75. 65.] Highest average: 85.0 Top student: Samadhan Students with average >= 75: ['Samadhan' 'Pradnya']

This mini project demonstrates how NumPy can calculate averages and filter students without requiring a separate calculation for each student.

18. Common Beginner Mistakes

Mistake 1: Incorrect indexing

An array with five elements uses indices 0 through 4. Accessing index 5 raises an IndexError.

Mistake 2: Forgetting the exclusive stop index

A slice such as numbers[1:4] includes indices 1, 2, and 3, but not 4.

Mistake 3: Reshaping into an incompatible shape

A 12-element array cannot be reshaped into a shape that requires 10 elements. The total element count must match.

Mistake 4: Using and instead of &

For element-wise comparisons across NumPy arrays, use & or | with parentheses around the individual conditions.

Mistake 5: Confusing axis values

For a two-dimensional array, axis=0 produces column-wise results and axis=1 produces row-wise results.

19. Beginner Self-Assessment

Try answering these questions without looking at the solutions above. You can use the answers to identify topics that need more practice.

Question 1

Which function creates a NumPy array from a Python list?

A. np.array()

B. np.reshape()

C. np.mean()

D. np.sort()

Question 2

What does np.sum(numbers) calculate?

A. The smallest element

B. The sum of array elements

C. The array dimensions

D. The data type

Question 3

What does numbers[-1] return?

A. The first element

B. The second element

C. The last element

D. The array length

Question 4

Which attribute gives the total number of array elements?

A. shape

B. ndim

C. size

D. dtype

Question 5

Which function generates evenly spaced values over an interval?

A. np.linspace()

B. np.unique()

C. np.min()

D. np.where()

Answer Key

Question 1: A Question 2: B Question 3: C Question 4: C Question 5: A

Summary

In this lesson, you practiced creating arrays, generating sequences, indexing, slicing, inspecting array attributes, performing arithmetic, calculating statistics, filtering values, reshaping arrays, and working with conditions. You also completed a student marks mini project and a beginner self-assessment.

Repeat the exercises without copying the solutions until you can write the programs independently. These fundamentals will prepare you for intermediate NumPy exercises involving multidimensional arrays, broadcasting, sorting, aggregation, and more advanced data-analysis tasks.