0
0
NumPydata~5 mins

Single element access in NumPy

Choose your learning style9 modes available
Introduction

We use single element access to get or change one specific value inside a numpy array. This helps us work with data piece by piece.

You want to check the value of a specific cell in a data table stored as an array.
You need to update one measurement in a large dataset without changing the rest.
You want to extract a single pixel value from an image represented as an array.
You want to compare one element in an array to a threshold.
You want to print or analyze just one number from a big array.
Syntax
NumPy
array[row_index, column_index]

Indexes start at 0, so the first element is at position 0.

For 1D arrays, use one index like array[index]. For 2D or more, use commas to separate indexes.

Examples
Access the second element (index 1) in a 1D array.
NumPy
import numpy as np
arr = np.array([10, 20, 30])
print(arr[1])
Access the element in the first row, second column of a 2D array.
NumPy
import numpy as np
arr = np.array([[1, 2], [3, 4]])
print(arr[0, 1])
Change the element in second row, third column to 100.
NumPy
import numpy as np
arr = np.array([[5, 6, 7], [8, 9, 10]])
arr[1, 2] = 100
print(arr)
Sample Program

This program shows how to get one temperature value from a 2D array and how to update one value.

NumPy
import numpy as np

# Create a 2D array representing temperatures in Celsius
temps = np.array([[22, 24, 19], [21, 23, 20], [20, 22, 18]])

# Access the temperature on the first day, second time slot
temp_value = temps[0, 1]
print(f"Temperature on day 1, time slot 2: {temp_value}°C")

# Change the temperature on day 3, time slot 3
temps[2, 2] = 25
print("Updated temperatures:")
print(temps)
OutputSuccess
Important Notes

Trying to access an index outside the array size will cause an error.

Negative indexes count from the end, like -1 is the last element.

Summary

Single element access lets you read or change one value in a numpy array.

Use zero-based indexes inside square brackets, separated by commas for multi-dimensional arrays.

This is useful for precise data handling and updates.