0
0
Data Analysis Pythondata~5 mins

Array indexing and slicing in Data Analysis Python

Choose your learning style9 modes available
Introduction

We use array indexing and slicing to pick specific parts of data from a list or array. It helps us focus on the data we need.

You want to get the first 5 days of sales data from a month.
You need to select every other item from a list of temperatures.
You want to extract a specific column or row from a table of numbers.
You want to reverse the order of a list of names.
You want to get a subset of data for analysis without changing the original data.
Syntax
Data Analysis Python
import numpy as np

# Create an array
array = np.array([10, 20, 30, 40, 50])

# Indexing: get one element by position
value = array[0]

# Slicing: get a part of the array
subset = array[start:stop:step]

Indexing starts at 0, so the first element is at position 0.

Slicing uses start (inclusive), stop (exclusive), and step (optional) to select elements.

Examples
Gets the first element, which is 5.
Data Analysis Python
import numpy as np
array = np.array([5, 10, 15, 20, 25])

# Indexing first element
first_element = array[0]
print(first_element)
Gets elements at positions 1 and 2, which are 10 and 15.
Data Analysis Python
import numpy as np
array = np.array([5, 10, 15, 20, 25])

# Slicing from index 1 to 3 (3 not included)
slice_part = array[1:3]
print(slice_part)
Gets elements at positions 0, 2, 4: 5, 15, 25.
Data Analysis Python
import numpy as np
array = np.array([5, 10, 15, 20, 25])

# Slicing with step: every other element
step_slice = array[::2]
print(step_slice)
Gets the last element, which is 25.
Data Analysis Python
import numpy as np
array = np.array([5, 10, 15, 20, 25])

# Negative indexing: last element
last_element = array[-1]
print(last_element)
Sample Program

This program shows how to get single elements and parts of an array using indexing and slicing.

Data Analysis Python
import numpy as np

# Create an array of numbers
numbers = np.array([100, 200, 300, 400, 500])

print('Original array:', numbers)

# Indexing: get the third element (index 2)
third_element = numbers[2]
print('Third element:', third_element)

# Slicing: get elements from index 1 to 3 (3 not included)
slice_part = numbers[1:3]
print('Slice from index 1 to 3:', slice_part)

# Slicing with step: get every second element
step_slice = numbers[::2]
print('Every second element:', step_slice)

# Negative indexing: get last two elements
last_two = numbers[-2:]
print('Last two elements:', last_two)
OutputSuccess
Important Notes

Indexing and slicing are very fast operations with arrays.

Negative indexes count from the end of the array.

Common mistake: forgetting that the stop index in slicing is not included.

Use slicing when you want a part of the data without changing the original array.

Summary

Indexing gets one element by position.

Slicing gets a range or pattern of elements.

Remember: start is included, stop is excluded in slicing.