Numpy - Indexing, Slicing and Iterating
Indexing, slicing, and iterating over arrays are common operations in NumPy, and they work similarly to how they work in Python's built-in list
and tuple
objects.
To index an array, you can use the square brackets []
and specify the indices of the elements that you want to access. For example:
import numpy as np
# Create a one-dimensional array
x = np.array([1, 2, 3, 4])
# Access the second element of the array
y = x[1]
# Access the second and third elements of the array
z = x[1:3]
In NumPy, you can also use negative indices to index elements from the end of the array. For example:
# Access the last element of the array
y = x[-1]
# Access the last two elements of the array
z = x[-2:]
To slice an array, you can use the colon :
operator to specify a range of indices to include in the slice. For example:
# Create a two-dimensional array
x = np.array([[1, 2, 3], [4, 5, 6]])
# Get a slice of the second row of the array
y = x[1,:]
# Get a slice of the second column of the array
z = x[:,1]
# Get a slice of the middle two rows and columns of the array
w = x[1:,1:]
To iterate over the elements of an array, you can use a for
loop. For example:
# Iterate over the elements of a one-dimensional array
for element in x:
print(element)
# Iterate over the elements of a two-dimensional array
for row in x:
for element in row:
print(element)