Member-only story
Hi everyone, welcome back. NumPy is a library for the Python programming language. NumPy is short for “Numerical Python” and is a popular library that is used in data science. NumPy is used specifically to work with arrays as it provides various functions and support. In this tutorial, we will go over how to slice arrays in NumPy.
Slicing Arrays
Slicing an array refers to items from one index to another index.
We can slice an array by using “[startIndex: endIndex: step]”. The step parameter is optional and we will go over that later. For now let’s see an example for slicing an array from a starting index to an end index:
import numpy as np
myArray = np.array([1, 2, 3, 4, 5])
print(myArray[1:3])Output:
[2 3]
In the example above, we have printed out a sliced array from index 1 to index 3. Notice that our output does not include our ending index. Our output only includes items at index 1 and index 2.
If a starting index is not passed and left blank, it will start at the beginning of the array, or index 0. Let’s see an example:
import numpy as np
myArray = np.array([1, 2, 3, 4, 5])
print(myArray[:3])Output:
[1 2 3]