Indexing and Slicing an Array in NumPy

image.png

Image Source

In my one of the last post a few months back, I gave a simple introduction on NumPy array. In this post, I am gonna write about how to index and slice an array using NumPy library. I created two array: the first one is one dimensional array and the another one is a two dimensional array.

import numpy as np

array_1d = np.array([57, 12, 89, 34, 76, 41, 23, 98])
array_2d = np.array([[42, 15, 87, 63, 28, 51],[96, 5, 37, 72, 20, 84],[10, 55, 78, 3, 69, 94
]])
array_1d.shape
array_2d.shape

image.png

The first array has 8 elements which means it has one row and 8 columns. The second array which is a two dimensional array has 3 rows and 6 columns. Lets say you want to access number 41 from the first array then you need to write the array name followed by brackets inside where the index number goes i.e. array_1d[5]. Please note that index number always starts at 0 in python and NumPy. You can get output as below:

image.png

Lets say I want to print the rest of the element after 76 in the first array. Then I would write like this: array_1d[4:]. It will print out the following:

image.png

You can simply reverse the array by writing array_1d[::-1].

image.png


Now for the rest of this post, we will be working with second dimensional array slicing. Lets first print out our required array which is array_2d.

image.png

Lets say you want to access number 72 which is in second rows fourth column. In order to access that number we will simply write array_2d[1,3]. where 1 means the second rows and 3 means the fourth column(Recall that indexing always starts from 0). We can see 72 in the output as below:

image.png

Now lets say that I want to slice out the following highlighted element from our second dimensional array.
image.png

For this we need to print out the remaining rows after index 1 and for the column value we need to print out from the first column to the fourth column(starting from second rows-index value 1). The output will be as below:

image.png

Now reversing the two dimensional array is very different as compared to reversing one dimensional array where the value is reversed from right to left. In two dimensional array, reversing can be done either row-wise or column-wise. We will reverse the array in both ways.

array_2d

# This will reverse the array column-wise
array_2d[::-1,:]

# This will reverse the array row-wise
array_2d[:,::-1]

You can see the following output:

image.png



0
0
0.000
1 comments
avatar

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

Thanks for including @stemsocial as a beneficiary, which gives you stronger support. 
 

0
0
0.000