Search⌘ K
AI Features

NumPy Array Indexing

Explore how to perform indexing and slicing on both 1-D and 2-D NumPy arrays, including how to manipulate array elements and handle memory references. This lesson helps you understand the basics needed to efficiently work with array data for predictive analytics using Python.

Indexing for a 1-D array

Just like normal arrays, elements of a NumPy array can also be accessed and changed through indexing. Through NumPy indexing, we can also access and change elements in a specific range.

The following code snippet provides an example of all these functionalities:

Python 3.5
import numpy as np
arr = np.arange(0,10,1) # Generate array with numbers from 0 to 9
print("The Array")
print(arr)
print("\nElement at index 5")
print(arr[5]) # Fetch element at index 5
print("\nElements in a range of 0 to 6")
print(arr[0:6]) # Fetch elements in a range
arr[0:6] = 20 # Assign a value to a range of elements
print("\nNew array after changing elements in a range of 0 to 6")
print(arr)

Note: The : inside the [] defines the range. The value to the left is the starting index and is inclusive. Meanwhile, the value on the right defines the ending index, which is exclusive; exclusive means that the value at the end index will not be considered for the ...