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 Intermediate Exercises

Welcome to the intermediate-level NumPy practice lesson at CIIT TRANING INSTITUTE. In this lesson, you will strengthen your NumPy skills through practical exercises covering multidimensional arrays, slicing, Boolean indexing, broadcasting, aggregation, reshaping, sorting, and vectorized operations. Each exercise includes a problem statement, solution, and expected output.

1. Working with Two-Dimensional Arrays

A two-dimensional NumPy array represents data in rows and columns. It is useful for student marks, sales reports, tables, and matrices. You can select individual elements, entire rows, or specific columns using indexing.

Exercise 1: Access Rows and Columns

Create a two-dimensional array containing marks for Samadhan, Pradnya, and Samiksha in three subjects. Display Pradnya's marks and the marks obtained by all students in the second subject.

import numpy as np marks = np.array([ [78, 85, 90], [88, 92, 81], [95, 87, 89] ]) print("Pradnya's marks:", marks[1]) print("Second subject marks:", marks[:, 1])

Expected output:

Pradnya's marks: [88 92 81] Second subject marks: [85 92 87]

The expression marks[1] selects the second row because NumPy indexing begins at zero. The expression marks[:, 1] selects every row from the second column.

Tip: In a two-dimensional array, use array[row, column] to select a single element and array[:, column] to select an entire column.

2. Array Slicing Practice

Slicing selects a portion of an array without writing a loop. The general syntax is array[start:stop:step]. The stop index is excluded from the selected range.

Exercise 2: Extract a Subarray

Given a 4 × 4 array, extract the first two rows and the last two columns.

import numpy as np data = np.array([ [10, 20, 30, 40], [50, 60, 70, 80], [90, 15, 25, 35], [45, 55, 65, 75] ]) result = data[:2, 2:] print(result)

Expected output:

[[30 40] [70 80]]

:2 selects rows at indices 0 and 1. 2: selects columns at indices 2 and 3.

Exercise 3: Reverse an Array

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

Expected output:

[50 40 30 20 10]

A step of -1 traverses the array in reverse order.

3. Boolean Indexing and Filtering

Boolean indexing selects elements based on a condition. The condition produces a Boolean array containing True and False values. NumPy returns the elements corresponding to True.

Exercise 4: Filter Passing Marks

Given the marks of three students, select all marks greater than or equal to 80.

marks = np.array([78, 88, 95, 67, 82, 74]) passed_marks = marks[marks >= 80] print("Passing marks:", passed_marks)

Expected output:

Passing marks: [88 95 82]

The expression marks >= 80 creates a Boolean condition. The resulting mask filters the original array.

Exercise 5: Filter Students with a Total Above 250

import numpy as np students = np.array(["Samadhan", "Pradnya", "Samiksha"]) marks = np.array([ [80, 85, 90], [90, 92, 88], [75, 80, 85] ]) totals = marks.sum(axis=1) selected_students = students[totals > 250] print("Totals:", totals) print("Selected students:", selected_students)

Expected output:

Totals: [255 270 240] Selected students: ['Samadhan' 'Pradnya']

sum(axis=1) calculates one total for each row. Boolean indexing then selects the student names whose totals exceed 250.

Important: Use & for element-wise AND and | for element-wise OR between NumPy conditions. Put parentheses around each condition.

4. Using np.where()

The np.where() function selects values based on a condition. It is useful for replacing values, classifying data, and creating conditional results without explicit loops.

Exercise 6: Classify Marks

marks = np.array([35, 68, 90, 42, 76]) status = np.where(marks >= 40, "Pass", "Fail") print(status)

Expected output:

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

The first argument is the condition, the second is the value returned when the condition is true, and the third is the value returned when false.

Exercise 7: Replace Negative Values with Zero

values = np.array([-5, 10, -2, 15, 0, 8]) cleaned = np.where(values < 0, 0, values) print(cleaned)

Expected output:

[ 0 10 0 15 0 8]

5. Broadcasting Operations

Broadcasting allows NumPy to perform operations on arrays with compatible shapes without manually repeating values. Dimensions are compatible when they are equal or when one of them is 1.

Exercise 8: Add a Value to Every Element

prices = np.array([100, 200, 300, 400]) updated_prices = prices + 50 print(updated_prices)

Expected output:

[150 250 350 450]

The scalar value 50 is applied to each element of the array.

Exercise 9: Add Column-wise Adjustments

sales = np.array([ [100, 200, 300], [150, 250, 350] ]) adjustments = np.array([10, 20, 30]) updated_sales = sales + adjustments print(updated_sales)

Expected output:

[[110 220 330] [160 270 380]]

The shape of sales is (2, 3) and the shape of adjustments is (3,). NumPy broadcasts the three adjustments across both rows.

Common mistake: Broadcasting does not make every pair of shapes compatible. For example, arrays with shapes (2, 3) and (2,) cannot be added directly because their trailing dimensions are 3 and 2. Reshape the second array to (2, 1) if row-wise broadcasting is intended.

6. Aggregation and Axis Operations

Aggregation functions such as sum(), mean(), min(), and max() summarize array data. The axis parameter controls which dimension is reduced.

Exercise 10: Calculate Row and Column Totals

marks = np.array([ [80, 85, 90], [90, 92, 88], [75, 80, 85] ]) print("Student totals:", marks.sum(axis=1)) print("Subject totals:", marks.sum(axis=0)) print("Average marks:", marks.mean())

Expected output:

Student totals: [255 270 240] Subject totals: [245 257 263] Average marks: 85.0

axis=1 reduces across columns to produce a result for each row. axis=0 reduces across rows to produce a result for each column. Without an axis, sum() or mean() operates over all elements.

7. Reshaping and Transposing

Reshaping changes the dimensions of an array while preserving its elements. Transposing swaps axes, which is particularly useful when preparing matrix data.

Exercise 11: Reshape a One-Dimensional Array

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 original array contains 12 elements. The requested shape (3, 4) also contains 12 positions, so the reshape is valid.

Exercise 12: Transpose a Matrix

matrix = np.array([ [1, 2, 3], [4, 5, 6] ]) transposed = matrix.T print(transposed) print("Shape:", transposed.shape)

Expected output:

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

8. Sorting and Unique Values

NumPy provides functions for sorting arrays, finding unique values, and locating positions that match a condition.

Exercise 13: Sort Values and Find Unique Elements

values = np.array([30, 10, 20, 10, 40, 30]) print("Sorted:", np.sort(values)) print("Unique:", np.unique(values))

Expected output:

Sorted: [10 10 20 30 30 40] Unique: [10 20 30 40]

np.sort() returns the sorted values, while np.unique() returns the distinct values in sorted order.

Exercise 14: Find Positions Matching a Condition

values = np.array([12, 25, 8, 32, 18]) positions = np.where(values > 20) print(positions[0])

Expected output:

[1 3]

np.where(condition) returns index arrays for positions where the condition is true. For a one-dimensional array, the first index array contains the matching positions.

9. Vectorized Calculations

Vectorization applies operations to whole arrays instead of using explicit Python loops. It often produces clearer and faster numerical code.

Exercise 15: Calculate Discounted Prices

prices = np.array([100, 250, 400, 500]) discounted_prices = prices * 0.90 print(discounted_prices)

Expected output:

[ 90. 225. 360. 450.]

Multiplying the array by 0.90 calculates prices after a 10% discount. NumPy performs the operation element-wise.

Tip: Prefer expressions such as prices * 0.90 over manually looping through every price when the calculation can be expressed as a NumPy operation.

10. Intermediate Challenge: Student Marks Analysis

Combine the concepts from this lesson to analyze marks for three students. Calculate total marks, average marks, identify students whose average is at least 80, and sort students by total marks.

Complete Solution

import numpy as np students = np.array(["Samadhan", "Pradnya", "Samiksha"]) marks = np.array([ [78, 85, 90], [92, 88, 95], [70, 75, 80] ]) totals = marks.sum(axis=1) averages = marks.mean(axis=1) print("Totals:", totals) print("Averages:", averages) qualified = students[averages >= 80] print("Students with average >= 80:", qualified) order = np.argsort(totals)[::-1] print("Ranking:") for index in order: print(students[index], totals[index])

Expected output:

Totals: [253 275 225] Averages: [84.33333333 91.66666667 75. ] Students with average >= 80: ['Samadhan' 'Pradnya'] Ranking: Pradnya 275 Samadhan 253 Samiksha 225

This exercise uses row-wise aggregation, Boolean filtering, sorting indices, and array indexing to produce a simple ranking report.

11. Practice Questions

Question 1

Given numbers = np.array([5, 10, 15, 20, 25, 30]), select values greater than 15.

Answer:

numbers[numbers > 15] # [20 25 30]

Question 2

Calculate the column-wise mean of the following array.

data = np.array([ [10, 20, 30], [20, 30, 40], [30, 40, 50] ]) print(data.mean(axis=0))

Answer:

[20. 30. 40.]

Question 3

Return the unique values from an array containing duplicates.

data = np.array([4, 2, 4, 3, 2, 5]) print(np.unique(data)) # [2 3 4 5]

Question 4

Reshape 24 sequential integers into a matrix with 4 rows and 6 columns.

data = np.arange(24).reshape(4, 6) print(data.shape) # (4, 6)

Question 5

Add 100 to every element of a two-dimensional array using broadcasting.

data = np.array([ [1, 2], [3, 4] ]) print(data + 100) # [[101 102] # [103 104]]

12. Common Mistakes to Avoid

  • Incorrect indexing: Remember that NumPy indexes start at zero.
  • Invalid reshape: The new shape must contain the same total number of elements as the original array.
  • Incorrect axis: Use axis=0 for column-wise reductions and axis=1 for row-wise reductions in a 2D array.
  • Missing condition parentheses: When combining conditions with & or |, put each comparison inside parentheses.
  • Broadcasting mismatch: Check the array shapes before performing operations between differently shaped arrays.
  • Confusing values and indices: np.argsort() returns sorting indices, whereas np.sort() returns sorted values.

Summary

In this lesson, you practiced multidimensional indexing and slicing, Boolean filtering, conditional selection, broadcasting, aggregation, reshaping, transposing, sorting, unique-value extraction, and vectorized calculations using NumPy.

Apply these techniques to real datasets such as student marks, sales figures, and numerical reports. Practice each example independently, modify the input values, and verify the output to build confidence before moving to advanced NumPy challenges.