Basic Slicing and indexing
Basic slicing and indexing is used to access a specific element or range of elements from a NumPy array.
Basic slicing and indexing only return the view of the array.
Consider the syntax x[obj] where “x” is the array and “obj” is the index. The slice object is the index in the case of basic slicing.
Basic slicing occurs when obj is :
- A slice object that is of the form start: stop: step
- An integer
- Or a tuple of slice objects and integers
All arrays generated by basic slicing are always ‘view’ of the original array.
Example: Basic Slicing in NumPy array
Python
import numpy as np # Arrange elements from 0 to 19 a = np.arrange( 20 ) print ( "\n Array is:\n " ,a) print ( "\n a[15]=" ,a[ 15 ]) # a[start:stop:step] print ( "\n a[-8:17:1] = " ,a[ - 8 : 17 : 1 ]) print ( "\n a[10:] = " ,a[ 10 :]) |
Output :
Array is:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
a[15]= 15
a[-8:17:1] = [12 13 14 15 16]
a[10:] = [10 11 12 13 14 15 16 17 18 19]
Ellipsis can also be used along with basic slicing. Ellipsis (…) is the number of: objects needed to make a selection tuple of the same length as the dimensions of the array.
Example: Basic slicing with ellipses
Python
import numpy as np # A 3 dimensional array. b = np.array([[[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]], [[ 7 , 8 , 9 ],[ 10 , 11 , 12 ]]]) print (b[..., 1 ]) #Equivalent to b[: ,: ,1 ] |
Output :
[[ 2 5]
[ 8 11]]
Basic Slicing and Advanced Indexing in NumPy
Indexing a NumPy array means accessing the elements of the NumPy array at the given index.
There are two types of indexing in NumPy: basic indexing and advanced indexing.
Slicing a NumPy array means accessing the subset of the array. It means extracting a range of elements from the data.
In this tutorial, we will cover basic slicing and advanced indexing in the NumPy. NumPy arrays are optimized for indexing and slicing operations making them a better choice for data analysis projects.
Prerequisites
Numpy in Python Introduction
Contact Us