NumPy Array Indexing

Array indexing in NumPy allows you to access and manipulate elements of arrays efficiently. It is similar to list indexing in Python but offers advanced features for multi-dimensional arrays. This capability is essential for processing data like population statistics from historic cities such as Madurai (Tamil Nadu, India) and Varanasi (Uttar Pradesh, India).

Key Topics

Indexing 1D Arrays

Access elements in a 1D array using their position (index). Indexing starts from 0 in NumPy arrays.

Example

# Indexing a 1D array
import numpy as np

population = np.array([1000, 1500, 2000, 2500, 3000])
print("First city population:", population[0])
print("Third city population:", population[2])

Output

First city population: 1000
Third city population: 2000

Explanation: The element at index 0 represents the first city, and the element at index 2 represents the third city. This indexing allows direct access to specific elements in the array.

Indexing 2D Arrays

Access elements in a 2D array by specifying their row and column indices. For example, rainfall statistics for Chennai (Tamil Nadu, India) and Jaipur (Rajasthan, India) can be represented as a 2D array.

Example

# Indexing a 2D array
rainfall = np.array([[100, 200], [150, 250]])
print("Rainfall in Chennai:", rainfall[0, 0])
print("Rainfall in Jaipur:", rainfall[1, 1])

Output

Rainfall in Chennai: 100
Rainfall in Jaipur: 250

Explanation: The first index specifies the row, and the second index specifies the column. For example, rainfall[0, 0] accesses the element in the first row and first column.

Negative Indexing

Negative indexing allows you to access elements from the end of an array. This is useful when analyzing recent data, such as the most recent year's statistics from Thanjavur (Tamil Nadu, India).

Example

# Negative indexing
recent_data = np.array([1990, 2000, 2010, 2020])
print("Most recent year:", recent_data[-1])
print("Second last year:", recent_data[-2])

Output

Most recent year: 2020
Second last year: 2010

Explanation: Negative indices start from -1 for the last element. For example, recent_data[-1] accesses the last element, while recent_data[-2] accesses the second-to-last element.

Key Takeaways

  • Flexible Indexing: Access array elements directly using indices, starting from 0 for the first element.
  • Advanced Indexing: Handle multi-dimensional arrays efficiently using row and column indices.
  • Negative Indexing: Retrieve elements from the end of an array using negative indices.
  • Real-World Applications: Process population and rainfall statistics for historic cities like Madurai, Varanasi, Chennai, and Jaipur.