Select an element or sub array by index from a Numpy Array
The elements of a NumPy array are indexed just like normal arrays. The index of the first element will be 0 and the last element will be indexed n-1, where n is the total number of elements.
Selecting a single element from a NumPy array
Each element of these ndarrays can be accessed using its index number.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Example: The following code shows how to access an element of a NumPy array.
numpyArr = 1 numpyArr[-1] = 4
In the first case, we accessed the first element of the array using its index number. In the second case we accessed the last element of the array by using negative indexes.
Selecting a sub array from a NumPy array (Slicing)
To get a sub-array, we pass a slice in place of the element index.
Here x and y are the starting and last index of the required sub-array.
Sub-Array= [4 5 6]
A sub-array starting from the 3rd index up to the 6th index ( excluding the last the 6th index ) was selected. You can slice a sub-array starting from the first element by leaving the starting index blank.
Example: The following code selects a sub-array starting from the first element.
Sub-Array= [1 2 3 4 5 6]
Similarly, leaving the left side of the colon blank will give you an array up to the last element.
Example: The following code selects a sub-array starting from a particular index up to the last index.
Sub-Array= [4 5 6 7 8 9]