Open In Colab

8: Basic Python Modules#

Python contains a number of built-in modules, which offer many useful mathematical, statistical, random and bone functions. To import a module, proceed as follows:

  • import module (imports the whole module)

  • import module as md** (give a nickname to the module)

  • from module import function** (import a function from the module)

import math
import statistics
import random
import os
import glob

You can also create your own modules and import them into other projects. A module is in fact a simple .py file that contains functions and classes

1. math and statistics modules#

The math and statistics modules are apparently very useful, but in data science, we will use their equivalents in the NUMPY package. It can nevertheless be interesting to see the basic functions.

print(math.pi)
print(math.cos(2*math.pi))
3.141592653589793
1.0
list = [1, 4, 6, 2, 5]

print(statistics.mean(list)) # average of the list
print(statistics.variance(list)) # variance of the list
3.6
4.3

2. Random module#

The random module is one of the most useful modules in Python. In data science, we will mostly use its NUMPY equivalent

random.seed(0) # set the random generator to always produce the same result

print(random.choice(list)) # choose an element at random from the list

print(random.random()) # generate a random number between 0 and 1

print(random.randint(5, 10)) # generate a random integer between 5 and 10
2
0.7579544029403025
8
random.sample(range(100), 10) # return a list of 10 random numbers between 0 and 100
[5, 33, 65, 62, 51, 38, 61, 45, 74, 27]
print('start list', list)

random.shuffle(list) #shuffle the elements of a list

print('shuffle list', list)
start list [1, 4, 6, 2, 5]
shuffle list [6, 1, 2, 4, 5]

3. OS and Glob modules#

The OS and GLob modules are essential to perform operations on your hard disk, like opening a file located in a certain working directory.

os.getcwd() # displays the current working directory
'/home/ubuntu/Documents/Projects/STI_FX_Intervention/book/docs/Python-Introduction/workshop'
print(glob.glob('*')) # contents of the current working directory
['19 - Seaborn.ipynb', '03 - Structures de Controles.ipynb', '07 - Built-in Functions.ipynb', '05 - Dictionnaires.ipynb', '10 - Numpy (les Bases).ipynb', 'fichier.txt', '13 - Numpy Broadcasting.ipynb', '18 - Pandas et Séries Temporelles.ipynb', '04 - Structures de données (Listes et Tuples).ipynb', '02 - Variables et Fonctions.ipynb', '06 - List Comprehension.ipynb', '17 - Pandas (les Bases).ipynb', '14 - Matplotlib (les Bases).ipynb', '11 - Numpy _ Indexing, Slicing, Boolean Indexing.ipynb', '16 - Scipy.ipynb', 'text.txt', '09 - Programmation Orientée Objet.ipynb', '12 - Numpy Maths et Statistiques.ipynb', '15 - Matplotlib Top Graphiques.ipynb', '08 - Modules de Bases.ipynb']