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.
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.
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:
| 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[1:5].
4. Creating an Array for Slicing
Before exploring different slicing techniques, create a NumPy array and examine its indexes.
5. Slicing with Start and Stop
You can specify the starting and stopping indexes to select a continuous range of elements.
| 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] |
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.
| 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[::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.
| 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] |
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.
[::-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:
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. |
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
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.
.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.
Expected Output
.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.
Practice Questions
- What is array slicing, and why is it useful?
- Explain the meaning of start, stop, and step.
- What is the output of
values[2:6]? - How can you select the last three elements of an array?
- How can you select every second element?
- What does
values[::-1]do? - How do you select the first two rows of a two-dimensional array?
- 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.