In this tutorial you will learn:
NumPy Array Slicing
We can also slice NumPy Array just like lists. When we slice the array in NumPy the same data is returned but the order is different. It is actually a view of the original array, whereas in case of lists slicing return a whole new list object. In order slice an array we pass there are three different ways. The first way is to pass the starting and ending index in square brackets and another way is to pass the starting index, ending index and step. Not passing any starting value means that the starting index value is 0 and not passing the ending value means we want the data till the last index value. Step value is 1 by default if we don’t write it explicitly.
1-D NumPy Array Slicing
Slicing 1-D NumPy is similar to slicing lists. We need to mention the starting and ending index in square brackets with a “:” in between. Let’s have a look at some examples.
- import numpy as np
- nparr = np.array([6,8,5,3,6,0,4,9,8,2])
- print(" ** 1D NumPy Array Slicing ** ")
Slicing with step 2
- print(" ** 1D NumPy Array Slicing with step 2 ** ")
Slicing with no start index but ending index is 3
- print(" ** 1D NumPy Array Slicing with default start ** ")
Slicing with no ending index but starting index is 3
- print(" ** 1D NumPy Array Slicing with default end ** ")
2-D NumPy Array Slicing
For slicing 2D arrays we need to write the index of array and then after the ‘,’ we can slice that array. Let’s look at some examples.
In this example we are accessing the second array and then slicing it from index 2 to 5 (not included).
- nparr = np.array([[6,8,5,3,6],[0,4,9,8,2]])
- print(" ** 2D NumPy Array Slicing ** ")
- print(nparr[1, 2:5])
Accessing second array with 0 as starting index and 3 as ending index.
- print(" ** 2D NumPy Array Slicing with default start for 2nd dimension ** ")
Accessing second array with 1 as starting index and default ending index.
- print(" ** 2D NumPy Array Slicing with default end for 2nd dimension ** ")
Slicing both arrays with first array starting from 0 to 4 and next array slicing from 1 to 3.
- print(" ** 2D NumPy Array Slicing with start, end for both dimensions** ")
Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.
Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.
FOR YOUR OWN SAFETY, PLEASE:
1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.