Skip to content

Indexing

A another powerful feature for data analysis and manipulation.

Let's perform basic operations such as indexing arrays, to manipulate and analyze data efficiently

Why Indexing?

Indexing is a fundamental concept in NumPy, allowing you to access specific elements or subsets of elements within an array.

A real-world example:

Suppose we have a dataset of stock prices, where each row represents a prices on dates and each column represents a open, high, low and close prices on particular day. We can use indexing to access specific prices or subsets of prices.

import numpy as np

# Create a NumPy array with stock prices
stock_prices = np.array([
    # [open, high, low, close]
    [749.90, 753.70, 739.00, 744.15],  # 24-10-2025
    [750.00, 755.65, 743.10, 745.90],  # 25-10-2025
    [762.00, 763.00, 738.00, 753.45],  # 26-10-2025

])

print("Prices: \n", stock_prices)

# Access a single element:
high_price = stock_prices[0, 1]
print("Stock high price on 24-10-2025: ", high_price)


# Access a subset of elements:
stock_prices_subset = stock_prices[0, :]
print("Stock prices on 24-10-2025: ", stock_prices_subset)

# Access a subset of elements:
close_prices = stock_prices[:, 3]
print("Close prices for all dates: ", close_prices)


# Access a subset of elements:
dates25_26_prices = stock_prices[1:3, :]
print("Prices for 25'th and 26'th dates: \n", dates25_26_prices)

In this example, we create a NumPy array stocks prices with dates prices, where each row represents a date and each column represents a prices. We then use indexing to access specific prices or subsets of prices.

  • We access a single element: Stock high price on 24-10-2025 using stock_prices[0, 1].
  • We access a subset of elements: Stock prices on 24-10-2025 using stock_prices[0, :].
  • We access a subset of elements: Close prices for all dates using stock_prices[:, 3].
  • We access a subset of elements: Prices for 25'th and 26'th dates using stock_prices[1:3, :].