NumPy ndarray.item()
The numpy.ndarray.item()
method is used to extract a scalar value from an array. It allows retrieving a single element by specifying its index. This method is useful when working with small arrays and needing direct access to a single element.
Syntax
ndarray.item(*args)
Parameters
Parameter | Type | Description |
---|---|---|
*args | int or tuple of ints, optional | Specifies the index of the element to be retrieved. It can be a single integer (for 1D arrays) or a tuple of integers (for multi-dimensional arrays). |
Return Value
Returns a scalar value that corresponds to the specified index in the array.
Examples
1. Extracting an Element from a 1D Array
In this example, we create a one-dimensional NumPy array and extract an element using the item()
method.
import numpy as np
# Creating a 1D NumPy array
arr = np.array([10, 20, 30, 40, 50])
# Extracting an element at index 2 (third element)
result = arr.item(2)
print(result) # Output: 30
Output:
30
The element at index 2
(third position) is extracted, which is 30
.
2. Extracting an Element from a 2D Array
Here, we extract an element from a two-dimensional array using a tuple index.
import numpy as np
# Creating a 2D NumPy array
arr = np.array([[1, 2, 3],
[4, 5, 6]])
# Extracting an element at row index 1, column index 2
result = arr.item((1, 2))
print(result) # Output: 6
Output:
6
The element at row index 1
and column index 2
is extracted, which is 6
.
3. Extracting the First and Last Elements from an Array
We demonstrate how to retrieve the first and last elements from a 1D array.
import numpy as np
# Creating a NumPy array
arr = np.array([5, 15, 25, 35, 45])
# Extracting the first element (index 0)
first_element = arr.item(0)
# Extracting the last element (index -1)
last_element = arr.item(-1)
print(first_element) # Output: 5
print(last_element) # Output: 45
Output:
5
45
Using index 0
retrieves the first element, and index -1
retrieves the last element of the array.
4. Using item()
on a Multi-Dimensional Array
We extract an element from a 3D array using a tuple of indices.
import numpy as np
# Creating a 3D NumPy array
arr = np.array([[[10, 20], [30, 40]],
[[50, 60], [70, 80]]])
# Extracting the element at depth index 1, row index 0, column index 1
result = arr.item((1, 0, 1))
print(result) # Output: 60
Output:
60
The element at depth index 1
, row index 0
, and column index 1
is retrieved, which is 60
.