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

Array Slicing Techniques

Learn how to select portions of NumPy arrays using slicing. Understand start, stop, and step values, negative indexes, reverse slicing, multidimensional slicing, and practical techniques for working with selected data.

1. Learning Objectives

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

  • Explain the purpose of array slicing in NumPy.
  • Understand the start, stop, and step values in a slice.
  • Select elements by specifying a range of indexes.
  • Use omitted values and negative indexes in slicing expressions.
  • Select alternate elements and reverse an array.
  • Slice rows and columns in two-dimensional arrays.
  • Understand the difference between a slice and an independent copy.
  • Apply slicing to practical data analysis tasks.
Beginner tip: Remember that NumPy indexes start at zero and the stop index in a slice is excluded. These two rules will help you understand most slicing expressions.

2. What Is Array Slicing?

Array slicing is a technique used to select a specific portion of an array. Instead of accessing each element individually, you can select a range of elements using a single expression.

Slicing is useful when you need to analyze a selected group of values, retrieve recent observations, select particular columns, or work with a smaller portion of a large dataset.

Example: Selecting Student Marks

Samadhan has a NumPy array containing the marks of students. He wants to display only the first four marks instead of printing every value in the array.

import numpy as np marks = np.array([72, 85, 68, 91, 77, 88, 95, 81]) selected_marks = marks[0:4] print(selected_marks) # Output: [72 85 68 91]

The expression marks[0:4] selects elements at indexes 0, 1, 2, and 3. The element at index 4 is not included.

3. Understanding Slicing Syntax

The general syntax for slicing a one-dimensional NumPy array is:

array[start:stop:step]
Component Description Example
Start The index at which selection begins. This index is included. array[2:6] starts at index 2.
Stop The index at which selection ends. This index is excluded. array[2:6] stops before index 6.
Step The interval between selected indexes. array[::2] selects every second element.
array[start:stop:step] start stop step Included Excluded Interval Start and stop define the range; step controls movement.
Figure 1: The three components of a NumPy slicing expression.
Remember: If the stop index is 5, index 5 itself will not be selected. The last selected index is normally 4 when using a positive step and a slice such as array[1:5].

4. Creating an Array for Slicing

Before exploring different slicing techniques, create a NumPy array and examine its indexes.

import numpy as np numbers = np.array([10, 20, 30, 40, 50, 60, 70, 80]) print(numbers) # Output: [10 20 30 40 50 60 70 80]
Array Index Map Index 0 Index 1 Index 2 Index 3 Index 4 Index 5 Index 6 Index 7 10 20 30 40 50 60 70 80 Positive indexes begin at zero.
Figure 2: Each array element can be selected using its index.

5. Slicing with Start and Stop

You can specify the starting and stopping indexes to select a continuous range of elements.

numbers = np.array([10, 20, 30, 40, 50, 60, 70, 80]) print(numbers[1:5]) # Output: [20 30 40 50] print(numbers[2:6]) # Output: [30 40 50 60] print(numbers[4:7]) # Output: [50 60 70]
Expression Selected Indexes Output
numbers[1:5] 1, 2, 3, 4 [20 30 40 50]
numbers[2:6] 2, 3, 4, 5 [30 40 50 60]
numbers[4:7] 4, 5, 6 [50 60 70]
Practical example: If a dataset contains daily measurements, slicing can select a particular range of days for closer analysis.

6. Omitting Start and Stop Values

The start and stop values are optional. When start is omitted, slicing begins at the beginning of the array. When stop is omitted, slicing continues to the end.

numbers = np.array([10, 20, 30, 40, 50, 60, 70, 80]) # Select elements from the beginning up to index 4 print(numbers[:4]) # Output: [10 20 30 40] # Select elements from index 3 to the end print(numbers[3:]) # Output: [40 50 60 70 80] # Select all elements print(numbers[:]) # Output: [10 20 30 40 50 60 70 80]
Expression Meaning
numbers[:4] Select from the beginning up to, but excluding, index 4.
numbers[3:] Select from index 3 through the end.
numbers[:] Select the entire array.

7. Slicing with a Step Value

The step value controls the interval between selected elements. A step of 1 selects consecutive elements, while a step of 2 selects every second element.

numbers = np.array([10, 20, 30, 40, 50, 60, 70, 80]) # Select every second element print(numbers[::2]) # Output: [10 30 50 70] # Select every second element starting at index 1 print(numbers[1::2]) # Output: [20 40 60 80] # Start at index 1, stop before index 7, and use step 2 print(numbers[1:7:2]) # Output: [20 40 60]
Selecting Every Second Element Index 0 Index 1 Index 2 Index 3 Index 4 Index 5 Index 6 Index 7 10 20 30 40 50 60 70 80 Selected: 10, 30, 50, 70 Green cells are selected by numbers[::2].
Figure 3: A step value of 2 skips one element between selections.
Important: The step value cannot be zero. An expression such as numbers[::0] raises a ValueError.

8. Slicing with Negative Indexes

Negative indexes count backward from the end of an array. The index -1 refers to the last element, -2 refers to the second-last element, and so on.

numbers = np.array([10, 20, 30, 40, 50, 60, 70, 80]) # Select the last three elements print(numbers[-3:]) # Output: [60 70 80] # Select all elements except the last two print(numbers[:-2]) # Output: [10 20 30 40 50 60] # Select from the fifth-last element up to the last element print(numbers[-5:-1]) # Output: [40 50 60 70]
Expression Explanation Output
numbers[-3:] Selects the last three elements. [60 70 80]
numbers[:-2] Excludes the last two elements. [10 20 30 40 50 60]
numbers[-5:-1] Starts at index -5 and stops before index -1. [40 50 60 70]
Practical example: Negative slicing is useful when you need the latest readings or the last few records without knowing the total number of elements in advance.

9. Reversing an Array Using Slicing

A negative step moves through an array in reverse order. The expression [::-1] is a common way to reverse the order of elements.

numbers = np.array([10, 20, 30, 40, 50]) reversed_numbers = numbers[::-1] print(reversed_numbers) # Output: [50 40 30 20 10]
Reversing an Array Original 10 20 30 40 50 Reversed 50 40 30 20 10
Figure 4: A negative step selects elements from right to left.
Remember: Slicing with [::-1] changes the order of the selected elements. It does not sort the values numerically.

10. Slicing Two-Dimensional Arrays

NumPy also supports slicing rows and columns in two-dimensional arrays. A comma separates the row selection from the column selection.

The general syntax is:

array[row_start:row_stop, column_start:column_stop]
matrix = np.array([ [10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120] ]) # Select the first two rows and columns at indexes 1 and 2 print(matrix[0:2, 1:3]) # Output: # [[20 30] # [60 70]]
Two-Dimensional Array Slicing Column 0 Column 1 Column 2 Column 3 Row 0 Row 1 Row 2 20 30 60 70 10 40 50 80 90 100 110 120 Selected: matrix[0:2, 1:3] Green cells represent the selected values.
Figure 5: Selecting a rectangular portion of a matrix.

Common Two-Dimensional Slices

Expression Description
matrix[0:2, :] Selects the first two rows and all columns.
matrix[:, 1:3] Selects all rows and columns at indexes 1 and 2.
matrix[1, :] Selects all elements in the second row.
matrix[:, 2] Selects the element at column index 2 from every row.
matrix[0:2, 1:3] Selects the first two rows and columns at indexes 1 and 2.
Beginner tip: In matrix[:, 1:3], the colon before the comma means all rows. The slice after the comma selects the required columns.

11. Slicing and Array Views

Basic NumPy slicing generally returns a view of the original array. A view shares the underlying data with the original array. Therefore, modifying a value through a view can also modify the original array.

Example: Modifying a Slice

numbers = np.array([10, 20, 30, 40, 50]) part = numbers[1:4] print(part) # Output: [20 30 40] part[0] = 999 print(part) # Output: [999 30 40] print(numbers) # Output: [10 999 30 40 50]

The original array changes because part is a view that shares data with numbers.

Creating an Independent Copy

Use the copy() method when you want to modify the selected values without changing the original array.

numbers = np.array([10, 20, 30, 40, 50]) part_copy = numbers[1:4].copy() part_copy[0] = 999 print(part_copy) # Output: [999 30 40] print(numbers) # Output: [10 20 30 40 50]
Important: Basic slicing usually produces views, while advanced indexing with integer arrays or Boolean arrays generally produces copies. Use .copy() explicitly whenever independent data is required.

12. Practical Example: Student Marks Analysis

Pradnya is analyzing marks stored in a NumPy array. She needs to display selected marks, retrieve the last three entries, select alternate values, and create an independent selection for further calculations.

import numpy as np marks = np.array([72, 85, 68, 91, 77, 88, 95, 81]) # Select the first four marks first_four = marks[:4] print("First four:", first_four) # Select the last three marks last_three = marks[-3:] print("Last three:", last_three) # Select alternate marks alternate_marks = marks[::2] print("Alternate marks:", alternate_marks) # Reverse the order of the marks reverse_marks = marks[::-1] print("Reverse marks:", reverse_marks) # Create an independent selection selected_marks = marks[2:6].copy() selected_marks[0] = 100 print("Original marks:", marks) print("Updated selection:", selected_marks)

Expected Output

First four: [72 85 68 91] Last three: [88 95 81] Alternate marks: [72 68 77 95] Reverse marks: [81 95 88 77 91 68 85 72] Original marks: [72 85 68 91 77 88 95 81] Updated selection: [100 91 77 88]
What did we learn? Slicing makes it easy to select data for analysis. Using .copy() ensures that changing the selected values does not affect the original marks array.

13. Common Slicing Mistakes

Mistake Explanation Correct Approach
Expecting the stop index to be included The stop index is excluded from the selection. Choose the stop value according to the exclusive-stop rule.
Using a zero step A slice cannot use zero as its step value. Use a non-zero positive or negative step.
Assuming a slice is always independent Basic slices generally share data with the original array. Use .copy() when independent data is needed.
Mixing up rows and columns Two-dimensional slicing separates row and column selections with a comma. Use array[rows, columns].
Using a negative step without checking the order A negative step traverses the array backward. Check the start and stop values when using negative steps.

14. Classroom Practical Activity

Activity: Working with Selected Data

At CIIT TRANING INSTITUTE, Samiksha will use NumPy slicing to examine a dataset and extract the values required for analysis.

import numpy as np values = np.array([5, 10, 15, 20, 25, 30, 35, 40, 45, 50]) # First five values print(values[:5]) # Values from index 3 up to index 7 print(values[3:7]) # Every second value print(values[::2]) # Last four values print(values[-4:]) # Reverse the array print(values[::-1]) # Create an independent selection selection = values[2:6].copy() selection[0] = 999 print("Original:", values) print("Selection:", selection)

Practice Questions

  1. What is array slicing, and why is it useful?
  2. Explain the meaning of start, stop, and step.
  3. What is the output of values[2:6]?
  4. How can you select the last three elements of an array?
  5. How can you select every second element?
  6. What does values[::-1] do?
  7. How do you select the first two rows of a two-dimensional array?
  8. What is the difference between a slice and a copy?

Challenge Exercise

Create a two-dimensional array containing marks for three students across four subjects. Write slicing expressions to:

  • Select the first two students.
  • Select the last two subjects for every student.
  • Select the first two students and subjects at indexes 1 and 2.
  • Extract the marks of the second student.
  • Create an independent copy of a selected portion and modify it.

Summary

In this lesson, we learned how to select portions of NumPy arrays using slicing. The syntax array[start:stop:step] allows us to specify where selection begins, where it ends, and the interval between selected elements.

We explored omitted start and stop values, negative indexes, step slicing, reversing arrays, and selecting rows and columns from two-dimensional arrays. We also learned why basic slices generally share data with the original array and how .copy() creates an independent copy.

Practice these slicing techniques with different arrays to become comfortable selecting exactly the data you need.