Modules and NumPy Arrays#

A lot of the power of Python comes from the fact that it has a lot of MODULES that you can use. A module gives us additional functions we can use in our code.

Build-in Modules#

On your Pythoneering journey, you will come across a lot of modules that are built into Python. These modules are already installed and ready to use.

Math#

This module contains a lot of handy mathematical functions that you can use in your code.

#we import modules using the import keyword
import math

#access functions of the module using the dot operator
print(math.sqrt(16))
print(math.radians(90))
4.0
1.5707963267948966

To easier access the functions in the module, you can import the functions directly.

from math import sqrt, radians

print(sqrt(16))
print(radians(90))
4.0
1.5707963267948966

To further ease our work, we can rename the modules we access in our code:

import math as m #renaming the math module to m by using the as keyword

print(m.sqrt(16))
print(m.radians(90))
4.0
1.5707963267948966

Random#

This module contains functions that allow us to generate random numbers.

import random as rd

print(rd.randint(1, 10))
print(rd.random())
3
0.6995858227698856

External Modules#

These are modules that are not built into Python. You have to install them before you can use them. You can either use your IDE’s package manager or use the pip command in the terminal.

Let’s go through both methods.

Package Manager#

Most IDEs have a package manager that you can use to install external modules. Let’s install numpy using the package manager in PyCharm.

pip install#

You can also install external modules using the pip command in the terminal.

To install a module, you use the command:

pip install module_name

Let’s install the matplotlib and pandas module using the pip command.

NumPy#

NumPy is a powerful module that allows us to work with arrays and matrices. In this chapter we will start with some numpy commands. Numpy is commonly shortened to np when imported.

import numpy as np

With numpy we can create arrays using the array() function. Those arrays can be used to perform mathematical operations on.

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

We can create multidimensional arrays using numpy. In MATLAB we would use the following syntax:

a = [1, 2, 3; 4, 5, 6];

With numpy we use:

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

To index a numpy array, we use the same syntax as we would use for a list.

print(b[0, 1]) #the element in the first row and second column
#to get the first row
print(b[0])
#or
print(b[0, :]) #the colon means all elements in that dimension
2
[1 2 3]
[1 2 3]

With arange() we can create an array with a range of numbers.

c = np.arange(10) #this will create an array with numbers from 0 to 9
print(c)
[0 1 2 3 4 5 6 7 8 9]

We can also create arrays with zeros or ones using the zeros() and ones() functions. You should notice this from MATLAB. NOTE: The zeros() and ones() functions take a tuple as an argument of size if we want to specify a multidimensional size of the array.

d = np.zeros((3, 3)) #this will create a 3x3 array with zeros
print(d)
[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]

Unlike in MATLAB, a single digit as the size of the array will create a 1D array.

a = np.zeros(3)
print(a)
[0. 0. 0.]

We can also create “column” or “row” vectors using the reshape() function or specifying the size of the array when creating it.

b = np.zeros((3, 1)) #this will create a 3x1 array
print(b)
print(b.reshape(1, 3)) #this will reshape the array to a 1x3 array
[[0.]
 [0.]
 [0.]]
[[0. 0. 0.]]

Some fun facts about reshape():

  • The number of elements in the reshaped array must be the same as the number of elements in the original array.

  • If you are unsure about a dimension, you can use -1. Numpy will automatically calculate the dimension for you. This is especially useful when you want to reshape multiple arrays with different sizes but a certain target size in one dimension.

  • The elements of the original array are filled row-wise into the reshaped array.

You can simply add or multiply arrays element-wise.

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(a + b) #no need for specification of element-wise operations like we had to with matlab (./)
print(a * b)
[5 7 9]
[ 4 10 18]

CAVE: This is substantially different from adding or multiplying lists. Using the + operator on lists will concatenate the lists. Using the * operator on lists will repeat the list.

a = [1, 2, 3]
b = [4, 5, 6]
print(a + b) #this will concatenate the lists
print(a * 2) #this will repeat the list
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 1, 2, 3]

Merging arrays is also possible with numpy. We can use the concatenate() function to merge arrays.

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = np.concatenate((a, b))
print(c)
[1 2 3 4 5 6]

We can also merge arrays in multiple dimensions. Here we have two possibilities:

#if we have 2D arrays we can concatenate along the columns
a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([[7, 8, 9], [10, 11, 12]])
c = np.concatenate((a, b), axis=0) #axis=0 means we are concatenating along the first axis (rows)
print(c)
c = np.concatenate((a, b), axis=1) #axis=1 means we are concatenating along the second axis (columns)
print(c)
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]
[[ 1  2  3  7  8  9]
 [ 4  5  6 10 11 12]]

Task: What happens if we try to concatenate two arrays of different sizes?

At the end of this session, let us take a look at the np.linspace() function. This function creates an array with a specified number of elements between two numbers.

a = np.linspace(0, 10, 5) #this will create an array with 5 elements between 0 and 10
print(a)
[ 0.   2.5  5.   7.5 10. ]

Of course you can go backwards.

a = np.linspace(10, 0, 5) #this will create an array with 5 elements between 10 and 0
print(a)
[10.   7.5  5.   2.5  0. ]

We can also create a 2D array with np.linspace() in conjunction with reshape().

a = np.linspace(0, 10, 6).reshape(2, -1) #this will create a 2x3 array with 6 elements between 0 and 10
print(a)
[[ 0.  2.  4.]
 [ 6.  8. 10.]]

A useful way to get the shape of an array is the shape attribute of the array.

a = np.zeros((3, 5))
print(a.shape)
(3, 5)

Task: Find a way to concatenate these two arrays along the rows (so below each other).

a = np.linspace(0, 10, 6)
b = np.linspace(10, 0, 6)