0
0
NumPydata~5 mins

Why indexing matters in NumPy

Choose your learning style9 modes available
Introduction

Indexing helps you quickly find and use specific parts of your data. It saves time and makes your work easier.

You want to get a single value from a big table of numbers.
You need to change some values in a list without touching the rest.
You want to analyze only a part of your data, like one column or row.
You want to combine or compare specific parts of two datasets.
You want to filter data based on conditions, like all numbers bigger than 10.
Syntax
NumPy
array[index]
array[start:stop]
array[row_index, column_index]

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

Slicing uses start (included) and stop (excluded) positions.

Examples
Gets the third item (index 2) from the array, which is 30.
NumPy
import numpy as np
arr = np.array([10, 20, 30, 40])
print(arr[2])
Gets items from index 1 up to but not including 3, so 20 and 30.
NumPy
arr = np.array([10, 20, 30, 40])
print(arr[1:3])
Gets the item in second row, first column, which is 3.
NumPy
matrix = np.array([[1, 2], [3, 4]])
print(matrix[1, 0])
Sample Program

This program shows how to get and change parts of a 2D array using indexing. It prints specific values and the updated array.

NumPy
import numpy as np

# Create a 2D array
data = np.array([[5, 10, 15],
                 [20, 25, 30],
                 [35, 40, 45]])

# Get the value in the first row, second column
value = data[0, 1]
print(f"Value at row 0, column 1: {value}")

# Get the entire second row
second_row = data[1, :]
print(f"Second row: {second_row}")

# Get the last column
last_column = data[:, 2]
print(f"Last column: {last_column}")

# Change the value at row 2, column 0
data[2, 0] = 100
print("Updated data:")
print(data)
OutputSuccess
Important Notes

Remember that indexing starts at 0, not 1.

Using slicing (start:stop) does not include the stop index.

Changing values by indexing updates the original array.

Summary

Indexing lets you pick specific data quickly.

You can get single values, rows, columns, or slices.

Indexing helps you change data easily and efficiently.