0% found this document useful (0 votes)
20 views

NumPy Crash Course

Uploaded by

Aslam Waris
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

NumPy Crash Course

Uploaded by

Aslam Waris
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

NumPy

Crash
Course

ABBAS ALI
NumPy Crash Course eBook

Table Of Contents
Introduction
Set-Up

Chapters:

1. Creating an array from a Python list

2. NumPy Datatypes

3. Creating arrays with different dimensions

4. Attributes of NumPy array

5. Creating arrays using NumPy functions

6. Array Indexing

7. Array Slicing

8. Array Reshaping

9. Array Concatenation and Splitting

10. NumPy Universal Functions (Ufuncs)

Source code
What’s Next?

Introduction

Hey there!

The fact that you are reading this course tells me you want to build a career around one of the
following fields,

Data Analytics

NumPy Crash Course eBook 1


Data Science

Machine Learning

Deep Learning

NLP

Computer Vision

If you have done a little bit of Google search about what tools to learn to get into one of the
above fields, you know by now that after learning Python you need to start learning the Python
libraries.

And the first Python library that everyone prefers to learn is NumPy.

We learn NumPy first because every other library such as Pandas, SciPy, Matplotlib,
TensorFlow, PyTorch, and more are built on top of NumPy.

NumPy is the base of many popular libraries that we use to store and manipulate data thus if
you try to learn other libraries without learning NumPy you’re likely to struggle to grasp the
concepts.

Congratulations — You made a good choice to learn NumPy and this course will help you do
that.

In the world of Data, everything is just numbers or an array of numbers. Let’s say you are
working with images, the image needs to be converted into an array of numbers if we want to
work with it.

Do you know why? Because computers can only understand numbers.

Learning NumPy is a must if you want to get into Data Science, Data Analytics, Machine
Learning (ML), or anything related to Artificial Intelligence (AI).

You may ask, Do I need to learn NumPy if I want to get into Deep Learning (DL), Natural
Language Processing (NLP), or Computer Vision (CV)?

The answer is YES.

NumPy Crash Course eBook 2


Here is the reason — When you go more advanced in your learning journey towards DL, NLP,
and CV you will have to learn libraries like TensorFlow and PyTorch and the prerequisite for
learning them is knowing NumPy. If you try to learn them without any basic knowledge of
NumPy it is going to be really difficult for you.

I hope now you know how important it is for you to learn NumPy if you want to build a career
around AI and its related fields.

Before we move on, I want you to do a little set-up for coding because you are going to learn
NumPy in a code-first approach.

I don’t want you to just skim and read through the chapters, I want you to open your laptop,
grab a cup of coffee if you want, have this course on one tab, and on the other tab you should
have Google Colab Notebook.

After learning each topic you should execute the code on Google Colab Notebook.

The only prerequisite to take this course is knowledge of basic Python. If you know at least a
little bit of Python you will be able to go through this course with ease.

I assume that you know the basics of Python.

(If you don’t know Python yet, grab my FREE “Python for Absolute Newbies” ebook. It covers
all the basic topics. Use this link 👉
https://abbasaliebooks.gumroad.com/l/pythonforabsolutenewbies)

Let’s get hands-on.

If you don’t know how to set up Google Colab read the next Chapter.

Set-Up

Step 1: Open your favorite web browser.

NumPy Crash Course eBook 3


Step 2: Search “Google Colab”.

Step 3: Click on the First Link.

NumPy Crash Course eBook 4


Step 4: Click on “New notebook”. (If you haven’t signed in with your Gmail, first do that).

Step 5: Now you have a fresh notebook to start your NumPy Learning Journey.

NumPy Crash Course eBook 5


Step 6: Click on the “Untitled.ipynb” and change the name of the file to “Learning NumPy”.

Now you are all set to code.

Let’s code.

NumPy Crash Course eBook 6


Chapter-1: Creating an array from a Python list

First things first, you are going to start by importing the NumPy library with its very famous
alias np.

After that, check the version of your NumPy library using np.__version__.

import numpy as np
np.__version__

# 1.26.4

As of writing this code, my NumPy version is 1.26.4. You might have a newer version if you're
running this code at a later date.

It’s time to create your first NumPy array using a Python list (l = [1, 2, 3, 4]).

(I assume you are executing the code snippets on your Google Colab, if you are not coding
along then you are not going to learn anything. So, please code along.)

l = [1, 2, 3, 4, 5] # Python list

arr = np.array(l) # Converting Python list into an NumPy array


arr

# Output: array([1, 2, 3, 4])

In Google Colab, we don't need to use the print() function. We can simply write the variable
name and run the cell to see its output.

You know that [1, 2, 3, 4] is a Python list but when we pass the list inside
the np.array() function it gets turned into an array. To be specific a 1D (One-Dimensional)
array.

You may ask, why do we want to convert a list into an array? What is the use of doing that?

NumPy Crash Course eBook 7


Those are great questions. To understand this you first need to know the difference between a
list and an array.

See the below diagram to understand the difference.

When it comes to lists, it can store elements with different datatypes (we will learn about
datatypes in the next chapter) and it stores them in random memory locations which makes the

NumPy Crash Course eBook 8


element retrieving process slow.

Whereas when it comes to the array, it only stores elements of similar datatypes, and all the
elements are stored in a contiguous or continuous memory location. This makes arrays faster
than lists.

Thus, we prefer arrays over lists.

In the upcoming chapters, we will see what are datatypes and how to create 2D, 3D, and 4D
arrays.

It’s a great start already, let’s move to the next chapter, NumPy Datatypes.

Chapter-2: NumPy Datatypes

As I already told you, the only prerequisite for taking this course is knowing basic Python. If
you know basic Python you know what are datatypes.

Datatypes in NumPy are no different from datatypes in Python. We got the same,

int (e.g. 1, 5, 67, 4345, etc…)

str (e.g. ‘a’, ‘Ali’, ‘cherry’, “code”, ‘YOU ARE AWESOME’, etc…)

float (e.g. 5.33, 3.14, 0.432, 100.000, etc…)

bool (e.g. True or False)

In NumPy, we have an attribute(you will learn about attributes soon) called dtype to know the
datatype of an Array. We have many attributes in NumPy, we will learn about them in depth in
Chapter 4.

Now let’s create arrays of different datatypes one by one.

int

NumPy Crash Course eBook 9


arr1 = np.array([1, 2, 3, 4])
arr1.dtype

# OUTPUT: dtype('int64')

The 64 in (’int64’) suggests that each element in the array takes up 64 bits (8 bytes) of space.
If you want to reduce the memory usage you can change the data type from ‘int64’ to ‘int32’ or
‘int16’.

Here is how you do that,

arr1 = np.array([1, 2, 3, 4], dtype='int32')


arr1.dtype

# OUTPUT: dtype('int32')

If you don’t specify any value in the dtype parameter NumPy takes 64 bits as default.

Exercise: Now try changing the dtype parameter to ‘int16’ and run the cell.

Let’s move on to str.

str

When each element inside the array is enclosed in single or double quote the array consists of
string elements.

arr2 = np.array(['a', 'b', 'c', 'd'])


arr2.dtype

# OUTPUT: dtype('<U1')

NumPy Crash Course eBook 10


Don’t get confused by ‘<U1’. The U in ‘<U1’ means Unicode character and the 1 is the maximum
length of the elements in the NumPy array. As you can see all the elements in our array are of
length 1 that’s why we are getting ‘<U1’.

Let’s create elements of different lengths and see what we get.

arr2 = np.array(['apple', 'banana', 'cherry', 'dragon', 'Hello Worl


d!'])
arr2.dtype

# OUTPUT: dtype('<U12')

We got ‘<U12’ because the biggest string in our array is ‘Hello World!’ and its length is 12.

Exercise: Now create an array with a different set of elements with different lengths and
see what you get.

We can also convert an array containing int elements into str by passing ‘str’ inside the dtype
parameter. See the code below,

arr1 = np.array([1, 2, 3, 4], dtype=str)


arr1, arr1.dtype

# OUTPUT: dtype('<U1')

Let’s move on to float.

float

arr3 = np.array([1.2, 2.3, 3.4, 4.5])


arr3.dtype

NumPy Crash Course eBook 11


# OUTPUT: dtype('float64')

You can do the same thing that we did with the int datatype to change the bit value from 64 to
32 or 16.

Exercise: Change the dtype from ‘float64’ to ‘float16’.

Finally, let’s create an array with bool elements.

bool

arr4 = np.array([True, False, True, False])


arr4.dtype

True and False are the only two elements of type bool.

These are the 4 important NumPy datatypes you need to know.

Now, it’s time to learn how to create arrays with different dimensions.

Chapter-3: Creating arrays with different


dimensions

In the first chapter, we build a simple 1D array remember?

In this chapter, we are going to build arrays with different dimensions.

Each dimension can be called using different terms such as scalar, vector, matrix, and tensor.

NumPy Crash Course eBook 12


To be specific,

0D - Scalar

1D - Vector

2D - Matrix

3D or more - Tensor

Let’s code them one by one,

Scalar (0D)

A scalar doesn’t have any dimensions. It’s just a single value.

d0 = np.array(6)
d0, d0.ndim

# OUTPUT: (array(6), 0)

In the previous chapter, we say the dtype attributes which was used to know the datatype of
an array. Similarly, the ndim used in the above code is also an attribute that is used to know the
number of dimensions of an array.

The value of d0 is array(6).

The value of d0.ndim is 0 because it’s a scalar.

(You don’t have to worry too much about the attributes, we will cover them in the next Chapter)

Vector (1D)

d1 = np.array([1, 2, 3, 4])
d1, d1.ndim

# OUTPUT: (array([1, 2, 3, 4]), 1)

NumPy Crash Course eBook 13


A vector is just a list of numbers in a 1-dimensional array. You can think of it as a single column
without any rows.

Matrix (2D)

d2 = np.array([[1, 2, 3, 4],
[5, 6, 7, 8]])
d2, d2.ndim

""" OUTPUT: (array([[1, 2, 3, 4],


[5, 6, 7, 8]]), 2) """

When an array has both rows and columns, it is considered a 2D array or a matrix.

(If you have worked on any Machine Learning project you would know that when splitting the
dataset, we split them into two parts namely, features and labels. The features will have
multiple columns and rows exactly like a matrix but the labels will only have a single column
very much like a vector).

The above paragraph is out of the scope of this course thus if you didn’t understand anything
you don’t have to worry.

Just keep in mind that a matrix has both rows and columns but a vector only has a single
column.

Tensor (3D)

Anything above 2-dimension can be called as a tensor.

d3 = np.array([[[1, 2, 3],
[4, 5, 6]],
[[7, 8, 9],
[10, 11, 12]]])
d3, d3.ndim

""" OUTPUT: (array([[[ 1, 2, 3],


[ 4, 5, 6]],

NumPy Crash Course eBook 14


[[ 7, 8, 9],
[10, 11, 12]]]),3) """

Tensor (4D)

d4 = np.array([[[[1, 2], [3, 4]], [[5, 6], [7, 8]]],


[[[9, 10], [11, 12]], [[13, 14], [15, 16]]]])
d4, d4.ndim

""" OUTPUT: (array([[[[ 1, 2],


[ 3, 4]],

[[ 5, 6],
[ 7, 8]]],

[[[ 9, 10],
[11, 12]],

[[13, 14],
[15, 16]]]]), 4) """

You may ask, what types of data have these many dimensions?

The below bulleted points will answer your question.

Tabular data—2D matrix

Time series data or sequence data—3D tensors

Images—4D tensors

Video—5D tensors

Now you know how to create arrays of different dimensions using NumPy but before moving to
the next chapter, see the below image to understand the structures of scalar, vector, matrix,
and tensor.

NumPy Crash Course eBook 15


Let’s jump to the next chapter, but wait.

Are you coding along?

I hope you are.

Chapter-4: Attributes of NumPy array

If you take a person and list his attributes it would look something like this 👇,
Height: 5’7

Weight: 50 kg

Color: Black ( I am not a racist by the way).

Age: 24

etc…

Similarly, attributes for a NumPy array are,

dtype - Datatype

ndim - Number of Dimensions

shape - Shape of the array (which is just the number of rows and columns depending on
the dimensions)

size - Number of elements present in the array

NumPy Crash Course eBook 16


itemsize - Memory consumption of a single element in the array

nbytes - Total Memory consumption of an entire array

Let’s code them out,

dtype

We have already seen this, so let’s not spend more time on this.

arr1 = np.array([1, 2, 3, 4])


arr2 = np.array(['a', 'b', 'c', 'd'])
arr3 = np.array([1.1, 2.2, 3.3, 4.4])
arr4 = np.array([True, False, True, False])
arr1.dtype, arr2.dtype, arr3.dtype, arr4.dtype

# OUTPUT: (dtype('int64'), dtype('<U1'), dtype('float64'), dtype('bool'))

Exercise: Create different sets of arrays and find their datatype using the dtype attribute.

ndim
Again, we have seen this already but let’s just quickly go over them.

arr4 = np.array([1, 2, 3, 4])


arr5 = np.array([[1, 2, 3], [4, 5, 6]])
arr6 = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
arr4.ndim, arr5.ndim, arr6.ndim

# OUTPUT: (1, 2, 3)

In the above code, I created 3 arrays namely, arr4, arr5, and arr6. All these 3 arrays have
different dimensions, shapes, and sizes.

Using the ndim attributes we found the dimensions of these arrays.

NumPy Crash Course eBook 17


Let’s know the shape and size of these arrays using the shape and size attributes.

shape

arr4.shape, arr5.shape, arr6.shape

# OUTPUT: ((4,), (2, 3), (2, 2, 3))

The output says the shape of,

arr4 - (4, )

arr5 - (2, 3)

arr6 - (2, 2, 3)

Let’s break this down.

See arr4 it has just one set of square brackets ([]). And in that one set of square brackets, we
got 4 elements namely, 1, 2, 3, 4.

Thus, the shape is 4.

Now see arr5 it has two sets of square brackets. In the first set of square brackets, we got 2
elements namely, [1, 2, 3], [4, 5, 6], and in the second set of square brackets, we got 3
elements each namely, 1, 2, 3 and 4, 5, 6.

Thus, the shape is (2, 3).

To make this easy to understand imagine the array like a matrix,

[1, 2, 3]

[4, 5, 6]

The above matrix has 2 rows and 3 columns thus the shape is (2, 3).

NumPy Crash Course eBook 18


In arr6,

The first set of square brackets has 2 elements → [[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]
The second set of square brackets has 2 elements each → [1, 2, 3], [4, 5, 6] and [7, 8, 9], [10,
11, 12]
The third set of square brackets has 3 elements each → 1, 2, 3 | 4, 5, 6 and 7, 8, 9 | 10, 11, 12

Thus, the shape is (2, 2, 3).

I hope you understood the shape attribute concept clearly.

size

arr4.size, arr5.size, arr6.size

# OUTPUT: (4, 6, 12)

size attribute is a very easy concept to understand.

It gives the value of the number of actual elements present in the array.

In arr4, we have only 4 elements → 1, 2, 3, 4

In arr5, we have 6 elements → 1, 2, 3, 4, 5, 6


In arr6, we have 12 elements → 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12

Just count how many numbers are present in an array that is the size of that array. As simple
as that.

Now the next two attributes itemsize and nbytes are related to memory consumption. Let’s see
how they work.

itemsize

NumPy Crash Course eBook 19


arr4.itemsize, arr5.itemsize, arr6.itemsize

# OUTPUT: (8, 8, 8)

If you remember one of our previous lessons about datatypes you know that when we create
an array of integers by default it will be in the dtype of ‘int64’ which means each element in the
array takes up 8 bytes of memory.

That is what has happened in the above code.

The itemsize attribute gives us the memory consumption of a single element in the array.

Let’s try changing the dtype from ‘int64’ to ‘int32’.

arr4 = np.array([1, 2, 3, 4], dtype='int32')

arr4.itemsize, arr5.itemsize, arr6.itemsize

# OUTPUT: (4, 8, 8)

We just changed the dtype of arr4 from ‘int64’ to ‘int32’ because of that its single elements
memory consumption is reduced from taking up 8 bytes to 4 bytes.

Exercise: Try to change the dtype of arr5 and arr6 to ‘int16’ and see what happens

nbytes

nbytes attributes give the total memory consumption of the array.

arr4.nbytes, arr5.nbytes, arr6.nbytes

NumPy Crash Course eBook 20


# OUTPUT: (16, 48, 96)

In the itemsize section, we say that a single element in arr4 takes up 4 bytes of memory and in
arr4 we got a total of 4 elements(1, 2, 3, 4) thus 4 x 4 = 16 nbytes.

The total memory consumption is 16.

For arr5, a single element holds 8 bytes of memory space. We have a total of 6 elements in it.

Thus, 8 x 6 = 48 nbytes.

Exercise: Try to break down the total memory consumption of arr6.

Great! We are done with the NumPy attributes.

It’s time to learn how to create arrays using some NumPy functions.

Chapter-5: Creating arrays using NumPy functions

Till now we have been creating arrays by ourselves. But there are a few functions in NumPy
that allow us to create arrays from scratch.

You might not understand the use of these functions now but as you advance in your learning
journey everything everything will start to make sense to you.

As a beginner, have an open mind and learn the basics. Over time, you'll see how these
concepts fit together.

Below are the list of functions we are going to learn in this Chapter:

NumPy Crash Course eBook 21


zeros()

ones()

full()

arange()

linspace()

random()

randint()

eyes()

Let’s build NumPy arrays using these functions one by one.

zeros:

z = np.zeros((3, 4), dtype=int)


z

""" OUTPUT: array([[0, 0, 0, 0],


[0, 0, 0, 0],
[0, 0, 0, 0]]) """

In the above code (3, 4) is equivalent to (row, column).


Similarly, we can also create a 3D array with (depth, rows, columns) like the one below.

z = np.zeros((2, 5, 3), dtype=int)


z

""" OUTPUT: array([[[0, 0, 0],


[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],

[[0, 0, 0],
[0, 0, 0],
[0, 0, 0],

NumPy Crash Course eBook 22


[0, 0, 0],
[0, 0, 0]]]) """

Now you know how to create arrays filled with zeros in different dimension.

Let’s see how to create arrays filled with ones.

ones:

o = np.ones((4, 5), dtype=int)


o

""" OUTPUT: array([[1, 1, 1, 1, 1],


[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]]) """

Now, just 0s and 1s. We can fill an array with any number we want by using the full() method.

full:

f = np.full((2, 4), 9)
f

""" OUTPUT: array([[9, 9, 9, 9],


[9, 9, 9, 9]]) """

arange:

This is one of the most used built-in functions compared to other built-in functions in NumPy.

a = np.arange(2, 21, 2)
a

NumPy Crash Course eBook 23


# OUTPUT: array([ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20])

The parameter values (2, 21, 2) stand for (start, stop, step), which means it starts at 2 and ends
at 21, and it skips the 2nd value after each value.

For example, for 2 it jumps to 4, from 4 it jumps to 6, and so on.

We will be using this function a lot throughout this course, so use this function and try to
create different arrays.

linspace:

l = np.linspace(1, 2, 10)
l

""" OUTPUT: array([1. , 1.11111111, 1.22222222, 1.33333333, 1.44


444444,
1.55555556, 1.66666667, 1.77777778, 1.88888889, 2.
])

"""

The linspace() function finds a specified number of values between a given two numbers.

In the above code, the first two parameter values (1 and 2) are the given two numbers. The
linspace() functions will find 10 values of equidistance from each other.

To understand this easily see the below code.

l = np.linspace(2, 20, 10)


l

# OUTPUT: array([ 2., 4., 6., 8., 10., 12., 14., 16., 18., 20.])

NumPy Crash Course eBook 24


The output is 10 values between 2 and 20 where each value is equidistant from each other.

random:

Inside the NumPy library there is a module called random. And inside this random module we
got a method named random. That’s why we got np.random.random() in the below code.

The random() method gives us random number between 0 and 1.

We can only specify the shape. In the below code, I specified the shape as (5, 4).

rr = np.random.random((5, 4)) # Gives random numbers between 0 and 1


rr

""" OUTPUT: array([[0.63633551, 0.08796748, 0.81917062, 0.12715859],


[0.6638637 , 0.89355948, 0.14505798, 0.49973856],
[0.47773628, 0.33628658, 0.0651107 , 0.53675706],
[0.63973589, 0.28866727, 0.10723666, 0.55947122],
[0.14240055, 0.18737459, 0.17222864, 0.5487357 ]])
"""

If you want to create random number of your choice. You need to use the randint() method.

randint:

ri = np.random.randint(4, 10, (3,9))


ri

""" OUTPUT: array([[5, 6, 8, 8, 4, 8, 4, 5, 7],


[8, 7, 7, 9, 9, 6, 7, 6, 7],
[6, 8, 4, 4, 9, 9, 6, 5, 8]]) """

The above code creates an array with elements of random number between 4 and 10 of shape
(3, 9).

NumPy Crash Course eBook 25


Each time you run the above code cell in your Google Colab you will get different set of values.

If you want to get the same set of values every time you run the cell you need to set a seed
value.

In the below code, I seed the seed value as 38. But the seed value can be anything.

If you set the same seed value as me you will get the same set of random elements like me. If
you use a different seed value you will get a different set of random elements.

np.random.seed(38)
ri = np.random.randint(4, 10, (3,9))
ri

""" OUTPUT: array([[5, 7, 9, 7, 8, 8, 6, 5, 5],


[8, 4, 6, 5, 9, 9, 8, 7, 5],
[6, 9, 9, 9, 5, 4, 6, 7, 7]]) """

After setting the seed value using the seed() method, the output will not change every time I
run the cell.

Try it for yourself.

(I hope you are coding along).

eye:

Finally, the eye() method generates a matrix that will contain 1’s diagonally, see the below code,

e = np.eye(5, dtype=int)
e

""" OUTPUT: array([[1, 0, 0, 0, 0],


[0, 1, 0, 0, 0],
[0, 0, 1, 0, 0],

NumPy Crash Course eBook 26


[0, 0, 0, 1, 0],
[0, 0, 0, 0, 1]]) """

You will know the use of this function once you start learning about Computer Vision (CNN,
Filters, and more).

For now, focus on getting really good at the basics.

Exercise: Try out all the functions by yourself with different set of parameters.

We are good to move to the next chapter, Array Indexing.

Chapter-6: Array Indexing

Every element inside an array has an index value. The index value starts with 0.

The index value of the first element is 0, the second element is 1, the third element is 2, and so
on.

In this chapter, we are going to fetch the elements from arrays of different dimensions using
their index values.

It’s time to code.

Let’s create a 1D array with 10 random elements.

np.random.seed(45)
arr1 = np.random.randint(10, size=10)
arr1

NumPy Crash Course eBook 27


# OUTPUT: array([3, 0, 5, 3, 4, 9, 8, 1, 5, 9])

You will get the same set of values if you use the same seed value as me (45).

In the above output, the index value of 3 is 0, 0 is 1, 5 is 2, and so on.

Let’s fetch some values from the array using their index.

arr1[0], arr1[1], arr1[2]

# (3, 0, 5)

When you count the index from the beginning it starts with 0, 1, 2, etc…

But if you count the index from the reverse it starts with -1, -2, -3, etc…

For example, for an array like [1, 2, 3, 4, 5]. The reverse index value of 1 is -5, 2 is -4, 3 is -3, 4
is -2, and 5 is -1.

Let’s use the reverse index value and grab the last 3 values from the array arr1.

arr1[-1], arr1[-2], arr1[-3]

# (9, 5, 1)

We can not only grab the values using their index we can also change the value with a new
value.

Let’s see how to do that.

I am gonna change the last element of arr1 from 9 to 403.

NumPy Crash Course eBook 28


arr1[-1] = 403
arr1

# OUTPUT: array([ 3, 0, 5, 3, 4, 9, 8, 1, 5, 403])

Exercise: Try changing the values of other elements in arr1 using their reverse index.

Now you know how to fetch and change the element in a 1D array.

Let’s see how to fetch and change elements in a 2D array.

arr2 = np.random.randint(10, size=(3, 5)) # 3 rows | 5 columns


arr2

""" OUTPUT: array([[6, 8, 7, 8, 5],


[2, 8, 1, 6, 4],
[8, 4, 6, 4, 9]])

"""

Because this is a 2 dimensional array it has 2 index positions for each of the dimensions.

For example, the first dimension has 3 elements in it namely,

Elements Index value

[6, 8, 7, 8, 5] 0

[2, 8, 1, 6, 4] 1

[8, 4, 6, 4, 9] 2

index 0 1 2 3 4

0 6 8 7 8 5

1 2 8 1 6 4

2 8 4 6 4 9

If you want to fetch the first row you can simply use arr2[0].

NumPy Crash Course eBook 29


arr2[0]

# OUTPUT: array([6, 8, 7, 8, 5])

But if you want to fetch only the element 6 in the first row you need to use arr2[0, 0]. ([row,
column])

arr2[0, 0]

# OUTPUT: 6

If you want to fetch 5 you need to use arr2[0, 4].

Remember, rows and columns when fetching values from a 2D array. Specify the row first then
the column.

Let’s see some more code examples.

arr2[0, 0], arr2[1, 1], arr2[2, 2]

# OUTPUT: (6, 8, 6)

arr2[1, 2]

# OUTPUT: 1

arr2[-1, -1] # Element in the last row and column.

# OUTPUT: 9

NumPy Crash Course eBook 30


arr2[-2, -4] # Element in second last row and fourth last column.

# OUTPUT: 8

Try to fetch more elements by yourself.

Let’s change the value using the indices.

arr2[-2, -4] = 987


arr2

""" OUTPUT: array([[ 6, 8, 7, 8, 5],


[ 2, 987, 1, 6, 4],
[ 8, 4, 6, 4, 9]])

"""

I hope by now you know how to fetch and change value from both 1D and 2D NumPy arrays.

Let’s see some examples of indexing in a 3D NumPy array.

Exercise: Try to find the output of the code examples below by yourself.

arr3 = np.random.randint(10, size=(2, 3, 4))


arr3

""" OUTPUT: array([[[1, 6, 8, 8],


[1, 6, 0, 4],
[9, 8, 0, 9]],

[[2, 6, 7, 0],
[0, 2, 9, 2],
[6, 0, 9, 6]]])

NumPy Crash Course eBook 31


"""

arr3[1, 1, 3]

# OUTPUT: ___

arr3[-2, 1]

# OUTPUT: ___

arr3[1]

# OUTPUT: ___

Did you find the output? I hope you did.

We saw that we can change the value of an element in an array.

But we can also change the entire value inside an array.

arr3[0] = 0
arr3

""" OUTPUT: array([[[0, 0, 0, 0],


[0, 0, 0, 0],
[0, 0, 0, 0]],

[[2, 6, 7, 0],
[0, 2, 9, 2],
[6, 0, 9, 6]]])

"""

NumPy Crash Course eBook 32


Exercise: Try changing an entire value inside a 2D array.

It’s a wrap for this chapter.

Let’s learn how to slice NumPy arrays.

Chapter-7: Array Slicing

It’s time to do some slicing.

With the help of slicing we can break arrays into different pieces.

Even for slicing the arrays, we are going to use the index values of the elements.

A code example would be sufficient to make you understand slicing.

arr4 = np.arange(10)
arr4

# OUTPUT: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

We created an array with 10 elements. Let’s say I want the slice [4, 5, 6, 7] from this array. Then
I would do something like,

arr4[4: 8]

# OUTPUT: array([4, 5, 6, 7])

Inside the square brackets, we need to specify,

NumPy Crash Course eBook 33


[start: stop: step]

Here is an example,

arr4[1: 10: 2]

# OUTPUT: array([1, 3, 5, 7, 9])

Note: If you give the stop value as 10 it will only take up to 9. If you give the stop value as 9 it
will only take up to 8.

The step value 2 skips the second element.

Exercise: Try a different set of [start: stop: step] values and make a slice.

Let’s see how slicing works in a 2D array

np.random.seed(67)
arr5 = np.random.randint(1, 10, (3, 4))
arr5

""" OUTPUT: array([[4, 6, 6, 8],


[4, 7, 4, 8],
[9, 6, 4, 7]])

"""

If I want the middle row [4, 7, 4, 8] from this 2D array, I will do something like,

arr5[1:2]

# OUTPUT: array([[4, 7, 4, 8]])

NumPy Crash Course eBook 34


Let’s say I want to fetch the 4 red-colored elements from the array.

index 0 1 2 3

0 4 6 6 8

1 4 7 4 8

2 9 6 4 7

arr5[0:2, 1:3]

""" OUTPUT: array([[6, 6],


[7, 4]])
"""

[0:2] gives me the first 2 rows.


[1:3] gives me the middle two columns.

Let’s use negative indexing (or reverse indexing) and slice out the middle two columns.

index 0 or -4 1 or -3 2 or -2 3 or -1

0 or -3 4 6 6 8

1 or -2 4 7 4 8

2 or -1 9 6 4 7

arr5[-3:, 1:-1]

""" OUTPUT: array([[6, 6],


[7, 4],
[6, 4]])

"""

[-3:] - If you don’t specify anything after (:) it means it will fetch all the rows starting from -3.

[1: -1] - Here we are using both normal and reverse indexing. We are starting from the 1st index
to the last index which is -1.

Don’t get confused. It’s really simple.

Hey, wait.

Are you coding along?

NumPy Crash Course eBook 35


If you code and try out different code example by yourself you will be able to understand these
concepts with ease.

Here is an exercise for you.

arr6 = np.random.randint(1, 10, (2, 3, 4))


arr6

""" OUTPUT: array([[[5, 8, 2, 4],


[8, 9, 8, 3],
[6, 6, 4, 3]],

[[7, 7, 5, 9],
[4, 2, 5, 9],
[3, 8, 1, 8]]])

"""

Exercise: Explore your curiosity and slice the above 3D array into different pieces.

Done?

Great.

Let’s learn how to reshape NumPy arrays from one dimension to another.

Chapter-8: Array Reshaping

This is the easiest Chapter in this crash course.

Reshaping is simply, converting arrays of one dimension into another.

NumPy Crash Course eBook 36


We are not gonna take a lot of time on this Chapter. Let’s quickly jump on to the code examples
and learn how array reshaping works.

arr7 = np.arange(1, 10)


arr7

# OUTPUT: array([1, 2, 3, 4, 5, 6, 7, 8, 9])

We created a sample array arr7 with 9 elements.

We have 9 elements so we can only reshape this array into,

3x3

9x1

1x9

If we have an array with 10 elements then we can reshape that into,

2x5

5x2

10 x 1

1 x 10

I hope you can understand the concept.

Let’s reshape arr7.

arr7.reshape(3, 3)

""" OUTPUT: array([[1, 2, 3],


[4, 5, 6],
[7, 8, 9]])
"""

NumPy Crash Course eBook 37


arr7.reshape(9, 1)

""" OUTPUT: array([[1],


[2],
[3],
[4],
[5],
[6],
[7],
[8],
[9]])

"""

Exercise: Create an array with 10 elements and reshape it into,

2x5

5x2

10 x 1

1 x 10

Let’s see one more example of how to reshape an array with 20 elements.

arr8 = np.arange(1, 21)


arr8

""" OUTPUT: array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,


18, 19, 20])
"""

5 X 4 = 20

arr8.reshape(5, 4)

""" OUTPUT: array([[ 1, 2, 3, 4],


[ 5, 6, 7, 8],

NumPy Crash Course eBook 38


[ 9, 10, 11, 12],
[13, 14, 15, 16],
[17, 18, 19, 20]])

"""

4 X 5 = 20

arr8.reshape(4, 5)

""" OUTPUT: array([[ 1, 2, 3, 4, 5],


[ 6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]])

"""

2 X 5 X 2 = 20

arr8.reshape(2, 5, 2)

""" OUTPUT: array([[[ 1, 2],


[ 3, 4],
[ 5, 6],
[ 7, 8],
[ 9, 10]],

[[11, 12],
[13, 14],
[15, 16],
[17, 18],
[19, 20]]])

"""

Done with the reshaping of arrays.

Let’s learn how to join and split NumPy arrays.

NumPy Crash Course eBook 39


Chapter-9: Array Concatenation and Splitting

NumPy array concatenation and splitting are two important and opposite array operations.

Array concatenation is joining two or more arrays together. We can join two arrays either
horizontally or vertically. We will see that in-depth in this chapter.

Array splitting is splitting a single array into two or more pieces. We split the elements in the
array using their indices.

You will understand these two operations better via code examples than definitions. So, let’s
quickly create some arrays and try out these operations.

Let’s start with concatenation.

Array Concatenation

a1 = np.arange(1, 5)
a2 = np.arange(5, 9)
a1, a2

# OUTPUT: (array([1, 2, 3, 4]), array([5, 6, 7, 8]))

In the above code, I created two sample arrays a1 and a2 using arange().

Let’s join these two arrays using the np.concatenation() method.

np.concatenate([a1, a2])

# OUTPUT: array([1, 2, 3, 4, 5, 6, 7, 8])

NumPy Crash Course eBook 40


We just joined two 1D arrays using the concatenation method.

But when it comes to 2D or 3D arrays there are some additional methods that we can use to
join the two arrays in different axes.

Don’t worry if you didn’t understand the above paragraph. The following code example will
make things clear.

Let’s create two 2D arrays using arange().

a3 = np.arange(1, 10).reshape(3, 3)
a4 = np.arange(10, 19).reshape(3, 3)
a3, a4

""" OUTPUT: (array([[1, 2, 3],


[4, 5, 6],
[7, 8, 9]]),

array([[10, 11, 12],


[13, 14, 15],
[16, 17, 18]]))

"""

Let’s join them.

np.concatenate([a3, a4]) # concatenates by rows

""" OUTPUT: array([[ 1, 2, 3],


[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12],
[13, 14, 15],
[16, 17, 18]])

"""

The 2D arrays are joined vertically (row-wise).

NumPy Crash Course eBook 41


But what if I want to join them horizontally(column-wise)?

To join them horizontally, we need to pass the value 1 in the axis parameter.

np.concatenate([a3, a4], axis=1) # concatenates by columns

""" OUTPUT: array([[ 1, 2, 3, 10, 11, 12],


[ 4, 5, 6, 13, 14, 15],
[ 7, 8, 9, 16, 17, 18]])

"""

I hope you got the point.

Additionally, there are also 2 methods called,

vstack() &

hstack()

to do the same thing. Using vstack() we can join the arrays vertically. Using hstack() we can
join them horizontally.

Let’s try them.

np.vstack([a3, a4])

""" OUTPUT: array([[ 1, 2, 3],


[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12],
[13, 14, 15],
[16, 17, 18]])

"""

NumPy Crash Course eBook 42


np.hstack([a3, a4])

""" OUTPUT: array([[ 1, 2, 3, 10, 11, 12],


[ 4, 5, 6, 13, 14, 15],
[ 7, 8, 9, 16, 17, 18]])

"""

Exercise: Create three 2D arrays and use concatenation(), vstack(), and hstack() and
perform different join operations.

Now let’s do some splitting.

Array Splitting

Array splitting is just the opposite of array concatenation.

Let’s create an array with 10 elements and do some spitting on it.

a5 = np.arange(1, 10)
a5

# OUTPUT: array([1, 2, 3, 4, 5, 6, 7, 8, 9])

np.split(a5, [4])

# OUTPUT: [array([1, 2, 3, 4]), array([5, 6, 7, 8, 9])]

So, I passed a value [4] inside the np.split() method.

The value [4] is just the index value where I want to make the split.

NumPy Crash Course eBook 43


The index 4 belongs to the value 5 in the array. So, the array gets split into two one containing
values from index 0 to 3 and the other containing values from index 4 to the rest.

We can also split the array into more than 2 pieces let’s see how to do that.

np.split(a5, [3, 5, 7])

# OUTPUT: [array([1, 2, 3]), array([4, 5]), array([6, 7]), array([8, 9])]

Now, I passed 3 index values [3, 5, 7].

So, the elements before the index 3 will be the first split ([1, 2, 3]).

The elements from index 3 to index 5(value on index 5 not included) will be the second split
([4, 5]).

The elements from index 5 to index 7(value on index 7 not included) will be the third split ([6,
7]).

Finally, every element from index 7 will be the fourth split ([8, 9]).

Hope it’s clear.

Let’s do splitting on a 2D array.

np.split(a6, [2], axis=1)

""" OUTPUT: [array([[ 1, 2],


[ 5, 6],
[ 9, 10],
[13, 14],
[17, 18]]),

array([[ 3, 4],
[ 7, 8],
[11, 12],
[15, 16],
[19, 20]])]

"""

NumPy Crash Course eBook 44


As we saw in the array concatenation, about the two special methods vstack() and hstack().

We got,

vsplit() &

hsplit()

Let’s use them.

np.vsplit(a6, [3])

""" OUTPUT: [array([[ 1, 2, 3, 4],


[ 5, 6, 7, 8],
[ 9, 10, 11, 12]]),

array([[13, 14, 15, 16],


[17, 18, 19, 20]])]

"""

np.hsplit(a6, [2])

""" OUTPUT: [array([[ 1, 2],


[ 5, 6],
[ 9, 10],
[13, 14],
[17, 18]]),

array([[ 3, 4],
[ 7, 8],
[11, 12],
[15, 16],
[19, 20]])]

"""

Finally. You have reached the last chapter of the NumPy Crash Course—You are awesome.

NumPy Crash Course eBook 45


Chapter-10: NumPy Universal Functions (Ufuncs)

There are plenty of Ufuncs (Universal Functions) in NumPy but we are not going to look at
every one of them.

We are only going to learn the most essential functions.

The NumPy Ufuncs make array operations more efficient.

In this chapter, we are going to cover the Ufuncs of three major operations namely,

Arithmetic Operations

Aggregate Operations &

Comparison Operations

Let’s start with Arithmetic Operations using NumPy Universal Functions.

Arithmetic Operations

The NumPy’s Universal Functions for Arithmetic Operations are,

add()

subtract()

multiply()

divide()

floor_divide()

power()

mod()

Let’s create a sample array and execute all the above operations on it.

NumPy Crash Course eBook 46


import numpy as np
arr1 = np.arange(1, 11)
arr1

# OUTPUT: array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

add()

np.add(arr1, 5)

# OUTPUT: array([ 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])

The above code adds 5 to all the elements in the array arr1.

subtract()

np.subtract(arr1, 2)

# OUTPUT: array([-1, 0, 1, 2, 3, 4, 5, 6, 7, 8])

This code subtracts 2 from all the elements in the array arr1.

multiply()

np.multiply(arr1, 10)

# OUTPUT: array([ 10, 20, 30, 40, 50, 60, 70, 80, 90, 100])

I guess by now you know what is happening in the above code.

divide()

NumPy Crash Course eBook 47


np.divide(arr1, 100)

# OUTPUT: array([0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1

floor_divide()

np.floor_divide(arr1, 4)

# OUTPUT: array([0, 0, 0, 1, 1, 1, 1, 2, 2, 2])

Floor division removes all the decimal values.

power()

np.power(arr1, 2)

# OUTPUT: array([ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100])

mod()

np.mod(arr1, 2)

# OUTPUT: array([1, 0, 1, 0, 1, 0, 1, 0, 1, 0])

mod() gives us the reminder value of all the elements after being divided by 2.

Exercise: Perform all the arithmetic operations on a 2D array and see how it works.

That’s all for the arithmetic operations.

NumPy Crash Course eBook 48


Aggregate Operations

The NumPy’s Universal Functions for Aggregate Operations are,

mean()

median()

std()

var()

min()

max()

Let’s go through them one by one.

arr2 = np.array([1, 2, 3, 4, 5])


arr2

# OUTPUT: array([1, 2, 3, 4, 5])

We got 5 elements in arr2 ([1, 2, 3, 4, 5]).

Let’s find the mean, median, standard deviation (std), variance var), minimum value (min), and
maximum value (max)

mean()

np.mean(arr2)

# OUTPUT: 3.0

median()

np.median(arr2)

# OUTPUT: 3.0

NumPy Crash Course eBook 49


std()

np.std(arr2)

# OUTPUT: 1.4142135623730951

var()

np.var(arr2)

# OUTPUT: 2.0

min()

np.min(arr2)

# OUTPUT: 1

max()

np.max(arr2)

# OUTPUT: 5

Done.

Exercise: Use the aggregate functions on a 2D array. Just explore your curiosity. Try
different things and see how they work.

NumPy Crash Course eBook 50


Comparison Operations

The NumPy’s Universal Functions for Comparison Operations are,

equal()

less()

less_equal()

greater()

greater_equal()

not_equal()

Let’s see how these works.

import numpy as np
a1 = np.array([1, 2, 3, 4])
a2 = np.array([1, 0, 3, 7])
a1, a2

# OUTPUT: (array([1, 2, 3, 4]), array([1, 0, 3, 7]))

We are going to compare the elements inside the arrays a1 and a2.

When using comparison method we get an array of elements containing ‘True’ or ‘False’ based
on the comparison.

equal()

np.equal(a1, a2)

# OUTPUT: array([ True, False, True, False])

The first and third elements in both the arrays a1 and a2 are 1 and 3 respectively, thus the first
and third element of the output is ‘True’

NumPy Crash Course eBook 51


less()

np.less(a1, a2)

# OUTPUT: array([False, False, False, True])

less_equal()

np.less_equal(a1, a2)

# OUTPUT: array([ True, False, True, True])

greater()

np.greater(a1, a2)

# OUTPUT: array([False, True, False, False])

greater_equal()

np.greater_equal(a1, a2)

# OUTPUT: array([ True, True, True, False])

not_equal()

np.not_equal(a1, a2)

# OUTPUT: array([False, True, False, True])

NumPy Crash Course eBook 52


Exercise: Create two different 1D array and try out all the comparison methods.

Congratulations!!!

That’s a wrap!!!

You successfully completed the NumPy Crash Course.

Now you may ask, What’s Next?

Read the next chapter.

What’s Next?

The fact that you are reading this tells me how disciplined you are in learning.

Not many people can do what you have just done. Most people would have quit after
completing just 4 or 5 chapters but you completed all the 10 chapters (I believe you did) and
are eager to know what to do next.

I really appreciate that. You will go a long way and achieve more and more in your life.

The next step after learning NumPy is simple.

Start learning Pandas.

Stay tuned, for the Pandas Crash Course.

Don’t forget to connect with me using the below links.

NumPy Crash Course eBook 53


Connect with me:
https://x.com/xabbasalix

https://medium.com/@iabbasali
https://www.youtube.com/@Abbas_AIi
https://abbasaliebooks.gumroad.com/

Source Code

👇.
All the code examples used in this course can be found in my GitHub

https://github.com/AbbasAli01/AbbasAli/blob/main/NumPy_Crash_Course.ipynb

NumPy Crash Course eBook 54

You might also like