Working with Numpy Arrays: Indexing | by Kurtis Pykes | Towards Data Science

PyTrix will now be a weekly series where I present cool things that can be done in Python that are useful for Data Scientist. The last PyTrix tutorial can be found in the link below...
towardsdatascience.com
Link for the Github Repository below:
github.com
First, let’s start by explaining Numpy. Numpy is the de-facto library for scientific programming and is so commonly used amongst practitioners that it has its own standard when we import it — import numpy as np .
The Numpy framework provides us with a high-performance multidimensional array object, as well as useful tools to manipulate the arrays. On that note, we can describe numpy arrays as a grid of the same type values that is indexed via a tuple of non-negative integers.
We distinguish the number dimensions by the rank of the array. Additionally, the shape of the array is a tuple of integers that represent the size of the array along each of its dimensions.
Note: If you aren’t familiar with the rank terminology, in the link below Steven Steinke has an fantastic explanation.
medium.com
However, today’s series of PyTrix is about indexing arrays, therefore without further ado, let’s get into it!
The process of extracting individual elements, rows, columns or planes from multi-dimensional arrays is referred to as indexing.
There are multiple occasions in which we may wish to obtain some value(s) from an array during our Data Science projects. Depending on the dimension (or rank) of the matrix, we’d have to adopt various strategies to effectively perform this task.
For those that would like to read more about the np.array() class, the Documentation can be found here!
In the first example I will initialize a 1-D numpy array and print it:
Note: Assume the import for numpy from the previous section has been done
numbers= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]a= np.array(numbers)print(a)>>>> [ 1  2  3  4  5  6  7  8  9 10]
To access the elements within the array, we follow the exact same conventions for indexing into a normal python list or tuple data type:
print(f"Index 0: {a[0]}\nIndex 5: {a[5]}\nIndex 7: {a[7]}")>>>> Index 0: 1     Index 5: 6     Index 7: 8
Next, we will instantiate a 2 dimensional numpy array from a list of list. We already have one list initialized as numbers, we would have to create one more.
big_numbers= [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]b= np.array([numbers, big_numbers])print(b)>>>> [[  1   2   3   4   5   6   7   8   9  10]      [ 10  20  30  40  50  60  70  80  90 100]]
If we’d like to extract a single element from the 2-D array, we must first select the index, i, which is a pointer to the row of the matrix, then index, j, to select the column.
print(b[1, 4]) >>>> 50
This denotes that we selected row 1 and column 4 from our array.
I know my readers are very curious people. Therefore, you may be wondering what happens when you just pass the i index to our list...
print(b[0]) >>>> [ 1  2  3  4  5  6  7  8  9 10]
This returned the row vector at index 0. A Rank 1 array. What if we want to access a column vector?
print(b[:, 8])>>>> [ 9 90]
The : tells python that we we should take every row and we have broken it up with a “,” and 8 to tell python to take the rows only from column 8. However, we are getting slightly ahead of ourselves as this ties into slicing, which we will be discussing in next weeks PyTrix :).
Note: When we index or slice a numpy array, the same data is returned as a view of the original array, however accessed in the order that we have declared from the index or slice.
If a 2-D array can be instantiated with a list of list, then... you guessed it. A 3-D array is instantiated with a list of list of list — take a moment to let that sink in.
c= np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]],             [[10, 11, 12], [13, 14, 15], [16, 17, 18]],             [[19, 20, 21], [22, 23, 24], [25, 26, 27]]])print(c)>>>> [[[ 1  2  3]       [ 4  5  6]       [ 7  8  9]]            [[10 11 12]       [13 14 15]       [16 17 18]]            [[19 20 21]       [22 23 24]       [25 26 27]]]
We may think of a 3-D array as a stack of matrices where the first index, i, selects the matrix. The second index, j, selects the row and the third index, k, selects the column.
For example we will select the first matrix:
print(c[0])>>>> [[1 2 3]      [4 5 6]      [7 8 9]]
and if we want to select an individual element in the array, it is done as follows:
print(c[2, 1, 1])>>>> 23
To explain the above code, we printed from our 3-D array from matrix at index 2 , the row index 1, and column index 1.
I will break access of rows or columns into 3 scenarios for 3-D arrays.
Scenario 1: When we only specify the matrix, i and row ,j, this will in-turn return a specific row from the matrix we have selected.
print(c[0, 0]) >>>> [1 2 3]
This returned the matrix at index 0 and the row at index 0.
Scenario 2: When we want to access the column elements of a specific matrix, we fill the jth index with : to denote we want a full slice (all of the rows).
print(c[1, :, 2])>>>> [12 15 18]
This returned all the rows from matrix 1 that are in column index 2.
Scenario 3: Occasionally, we may want to access a value in the same row and column for each index.
print(c[:, 2, 0])>>>> [ 7 16 25]
This a list of each element in row index 2 and column index 0 for each matrix.
There are many options to indexing and learning them is a very set of skills that will be handy in your Data Science toolkit. For more on Indexing you can read the numpy Documentation which goes into indexing in great depth.
See the link below for access to the code used in this story.
github.com
If there is anything that you think I have missed, something that you’d like to point out to me, or if you are still unsure about something, your feedback is valuable. Send a response!
However, If you’d like to get in contact with me, I am most active on LinkedIn and I’d love to connect with you also.
www.linkedin.com
Here are some of my most recent work that you may also be interested in: