Indexing and Slicing

Indexing and slicing allow you to access specific elements or parts of an array. This is very important in Data Analytics because you often need to select specific rows, columns, or values from datasets.

First, import NumPy:

import numpy as np

Create a sample array:

arr = np.array([10, 20, 30, 40, 50])

Indexing in 1D Arrays

Indexing means accessing a single element using its position.

arr[0]   # First element
arr[2] # Third element

Remember: Indexing starts from 0.

Negative indexing:

arr[-1]  # Last element
arr[-2] # Second last element

Slicing in 1D Arrays

Slicing allows you to access a range of elements.

Syntax:

array[start:stop:step]

arr[1:4]    # Elements from index 1 to 3
arr[:3] # First three elements
arr[2:] # From index 2 to end
arr[::2] # Every second element

Indexing in 2D Arrays

Create a 2D array:

arr2 = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

Access a specific element:

arr2[0, 1]   # Row 0, Column 1

Access a full row:

arr2[1]

Access a full column:

arr2[:, 2]

Slicing in 2D Arrays

Select rows:

arr2[0:2]

Select specific rows and columns:

arr2[0:2, 1:3]

All rows, specific columns:

arr2[:, 0:2]

Boolean Indexing

Used for filtering data based on conditions.

arr[arr > 25]

For 2D arrays:

arr2[arr2 > 5]

Why Indexing and Slicing are Important

In Data Analytics, you use indexing and slicing to:

Select specific records
Filter data
Modify values
Prepare data for analysis
Extract meaningful information

Key Takeaway

Indexing and slicing help you access and manipulate specific parts of your dataset efficiently. Mastering these concepts is essential for working with NumPy arrays and real-world data.

Home » PYTHON FOR DATA ANALYTICS (PYDA) > NumPy > Indexing and Slicing