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.
Expected output:
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.
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.
Expected output:
:2 selects rows at indices 0 and 1.
2: selects columns at indices 2 and 3.
Exercise 3: Reverse an Array
Expected output:
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.
Expected output:
The expression marks >= 80 creates a Boolean condition.
The resulting mask filters the original array.
Exercise 5: Filter Students with a Total Above 250
Expected output:
sum(axis=1) calculates one total for each row.
Boolean indexing then selects the student names whose totals exceed 250.
& 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
Expected output:
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
Expected output:
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
Expected output:
The scalar value 50 is applied to each element of the array.
Exercise 9: Add Column-wise Adjustments
Expected output:
The shape of sales is (2, 3) and the shape
of adjustments is (3,).
NumPy broadcasts the three adjustments across both rows.
(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
Expected output:
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
Expected output:
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
Expected output:
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
Expected output:
np.sort() returns the sorted values, while
np.unique() returns the distinct values in sorted order.
Exercise 14: Find Positions Matching a Condition
Expected output:
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
Expected output:
Multiplying the array by 0.90 calculates prices after
a 10% discount. NumPy performs the operation element-wise.
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
Expected output:
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:
Question 2
Calculate the column-wise mean of the following array.
Answer:
Question 3
Return the unique values from an array containing duplicates.
Question 4
Reshape 24 sequential integers into a matrix with 4 rows and 6 columns.
Question 5
Add 100 to every element of a two-dimensional array using broadcasting.
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=0for column-wise reductions andaxis=1for 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, whereasnp.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.