Data Analysis with Python Course Guide
Data Analysis with Python Course Guide
Department of License
Course
Bachelor's Degree - Database Administration
Teachers
Teaching team
COURSE MATERIALS
Data analysis
with python
GENERAL OBJECTIVE: This course aims to provide the student with all the
necessary knowledge to analyze and visualize data with python.
SPECIFIC OBJECTIVES :
At the end of this course, the student should be capable of:
•To use Python's scientific libraries;
To analyze data with Numpy;
•To read a dataset with Pandas/explore a dataframe;
Manipulating data with Pandas;
To learn how to handle missing values;
To learn how to draw, customize, and interpret curves from
real data
To create the bar chart, the scatter plots,
histograms and box plots;
To tackle concrete and real data science projects.
CONTENT
CHAPTER I: INTRODUCTION
Table of Contents
CHAPTER I: INTRODUCTION
1. INSTALLATION PYTHON + JUPYTER NOTEBOOK .............................................. 6
2. Presentation Jupyter Notebook........................................................................................ 7
CHAPTER II: PYTHON RECAP
1. Variables & Data types........................................................................................ 8
Lists and dictionaries...................................................................................................... 8
3. Conditions IF/ELSE ........................................................................................................ 9
4. Loops FOR ................................................................................................................. 10
5. Functions Python........................................................................................................... 11
CHAPTER III: Numpy Library............................................................. 12
1. Introduction to Numpy ................................................................................................... 12
Predefined variabless ............................................................................................................ 12
Variable pi: NumPy allows obtaining the value of pi ................................. 12
2. Paintings with Numpy................................................................................................... 12
3. Size of a table......................................................................................................... 12
4. Lecture from a dataset with numpy
5. Types data with Numpy ..................................................................................... 13
Extraction of a value from a Numpy array ...................................................... 14
Slicing 2D Arrays ............................................................................................. 14
7. Extraction from a vector of values from a Numpy array...................................... 15
CHAPTER IV: Data Analysis with Numpy
1. Objectives 15
2. Comparisons ................................................................................................................ 16
3. Selection elements
Trigonometric functionss .................................................................................................. 17
Hyperbolic functions.......................................................................................... 17
Various functions
Useful functions for complex numberss ...................................................................... 18
CHAPTER V: Pandas Library
1. Introduction ................................................................................................................... 18
2. Presentation the datasett .................................................................................................. 18
CHAPTER VI: Data Manipulation with pandas ......................................................... 20
1. Introduction ................................................................................................................... 20
2. Transformation of a column ...................................................................................... 20
3. Operations mathematics between columnss .20
CHAPTER I: INTRODUCTION
Jupyter Notebook is a powerful tool that allows users of the Python language to create
and to share interactive documents containing dynamic and executable code,
visualizations of content, documentation texts and equations. The term 'notebook'
is related to the intrinsic nature of the tool that allows writing small pieces of executable code
(called 'cells'), to document them to explain what they do and to display the data
resulting from their execution. All of this is stored in a shareable document with others
users.
It is therefore particularly useful for prototyping algorithms or testing snippets of
code, in order to analyze the results and possibly add them to your main project. With
a notebook, no need to organize your code into functions, with a main, etc. You just have
need to write your code in the predefined blocks and execute it, to 'run some
Python
Jupyter Notebook for data analysis
Numeric variables
Numerical variables can be broken down into two distinct types:
The integers, which correspond to the set of positive whole numbers
or negatives (1, 2, 0, 123, -3, etc.);
Decimal numbers, which, in addition to integers, include the set of
decimal numbers (2.50 ; 5.99 ; -1.20 ; 2/3 ; etc.).
Character chairs
You will now explore a bit more the strings, which allow you to store
text in your variables. First of all, a bit of semantics: we call this
strings, because Python does not consider these variables as text as
such, but like a string of characters put together. Here's how you can define
strings in Python:
ville = "Brazzaville"
film = 'intouchables'
stringVide = ""
>>> ani1 = {}
>>> ani1["nom"] = "girafe"
>>> ani1["taille"] = 5.0
>>> ani1["poids"] = 1100
ani1
{'nom': 'girafe', 'taille': 5.0, 'poids': 1100}
3. Conditions IF/ELSE
This concept is one of the most important in programming. The idea is to say that it
if variable a has this value then do this else do that.
Let's take an example, we will assign a value to a variable and if this value is greater than
5, so we will increment the value by 1
>>> a = 10
>>> if a > 5:
... a=a+1
...
a
11
...
a
21
Condition elif
It is possible to add as many specific conditions as desired by adding the keyword
elif, contraction of 'else' and 'if', which could be translated as 'otherwise'.
>>> a = 5
>>> if a > 5:
... a=a+1
... elif a == 5:
... a = a + 1000
... else:
... a=a-1
...
a
1005
4. FOR Loops
Imagine, for example, that you want to display the elements of a list one after the other.
others. Given the current state of your knowledge, you would need to type something like:
If your list contains only 4 items, this is still doable, but imagine if it has more.
contains 100 even 1000! To remedy this, we need to use loops. Look at the example
following:
>>> animaux = ["girafe", "tigre", "singe", "souris"]
for animal in animals:
... print(animal)
...
giraffe
tiger
monkey
mouse
The variable animal is called an iteration variable, it successively takes on the different
values of the list animals at each iteration of the loop. We will see a little later in this
chapter where you can choose the name you want for this variable. It is created by
Python the first time the line containing the for is executed (if it already existed its
content would be overwritten). Once the loop is finished, this animal iteration variable will not be
not destroyed and will thus contain the last value of the list animals (here the string of
mouse characters).
Note well the types of variables used here: animals is a list on which we iterate, and
animal is a string because each element of the list is a string.
We will see later that the iteration variable can be of any type according to the list.
traversed. In Python, a loop always iterates over an object called sequential (that is to say a
object made up of other objects) such as a list. We will also see later other objects.
sequences on which we can iterate in a loop.
Already, pay attention to the colon character ':' at the end of the line starting with
for. This means that the for loop awaits a block of instructions, namely all the
instructions that Python will repeat in each iteration of the loop. This block is called
of instructions the body of the loop. How do we indicate to Python where this block starts and
Does it end? This is indicated only by the indentation, that is to say the offset towards the
right of the (or the) line(s) of the instruction block.
5. Python Functions
During your data analysis, you will regularly have to use multiple times
groups of instructions for a very specific purpose. One of the fundamental principles for everyone
Computer programmers aim to achieve maximum results for a minimum effort.
of efforts: a saying even says that a good programmer is a lazy programmer. It is
thanks to this somewhat "lazy" but incredibly effective principle, the idea of came about
functions. Functions allow grouping several instructions into a block that
will be called by a name.
Functions are not unique to Python; they are present in all programming languages.
IT. They particularly enable:
To reuse a piece of code that has already been written via the function name – it is therefore not
necessary to rewrite the entire portion of code each time;
To lighten a code and make it more readable!
There are many built-in functions in Python! In addition to those already seen, there are
for example:
len()a function that returns the length of an element. Do you remember the
String characters? Using this function on a string allows for
example of knowing how many characters it contains;
type()allows to display the type of a variable;
pow(a, b)allows calculating a raised to the power of b. It is equivalent to the notationa**b;
abs()returns the absolute value of a number.
1. Introduction to Numpy
First, you need to import the numpy package with the following instruction:
import numpy as np
Predefined variables
Variable pi: NumPy allows you to obtain the value of pi.
[Link]
3.141592653589793
Arrays (in English, array) can be created withc [Link]().We use brackets
to delimit lists of items in tables
a = [Link]([1, 2, 3, 4])
Display:
a
[1, 2, 3, 4]
type(a)
[Link]
3. Size of a table
(4,)
b = [Link]([[1, 2, 3],
[4, 5, 6]]
[Link](b)
(2, 3)
In the range [n:m], the element at indexn is included, but not the one with indexm. A way to
memorizing this mechanism involves considering that the limits of the slice are defined by
the numbers of the positions located between the elements, as shown in the diagram below:
Slicing of 2D arrays
a = [Link]([[1, 2, 3],
[4, 5, 6]])
a[0,1]
2
a[:,1:3]
array([[2, 3],
[5, 6]]
a[:,1]
array([2, 5])
a[0,:]
[1, 2, 3]
vecteur_1 = [Link]([1,2,3])
vector_2 = vector_1
vecteur_2[2] = 99
print("vecteur_1 =", vecteur_1)
print("vecteur_2 =", vecteur_2)
1. Objectives
Data analysis requires organizing the data in a more or less structured format.
common and corresponds to the table format. Also, with the incessant growth of
data sources, the size of the files where this data is stored is becoming increasingly
conséquente. Avec la bibliothèque Pandas, le Data Scientist peut s’affranchir de toutes ces
questions relatives au format et à la taille des données pour ne se concentrer que sur le problème
to solve.
2. Comparisons
The equality comparison operator == allows you to check if two quantities are equal or
no. The operator == returns True if the quantities are equal and false if the quantities are not.
equals. We can use the operator == with the all() function to check if all the
elements of the two tables are equal or not. The following code example shows us
how we can compare two arrays for equality with the == operator in Python.
3. Selection of elements
Condlist : The list of conditions that determine from which table of the list of
select the output elements are extracted. When multiple conditions are met, the
the first encountered in condlist is used.
Choice list :The list of tables from which the output elements are extracted. It
must be the same length as condlist.
Default : The item inserted into the output when all conditions are evaluated to False.
array = [Link]([1,2,3,4,5,5,6,7,8,8,9,9])
result = [Link](array, 0, 5)
print(result)
replace() takes two parameters, the first parameter is the regex pattern with which
you want to match the strings, and the second parameter is the string
for the corresponding string replacements.
There is also a third optional parameter in replace() that accepts an integer for
set the maximum number of replacements to execute. If you set 2 as a parameter
count, the replace() function will only match and replace 2 instances in the
chain.
Trigonometric functions
[Link](x) sinus
[Link](x) cosine
[Link](x) tangent
arcsine
[Link](x) arccosine
[Link](x) arctangent
Hyperbolic functions
[Link](x) hyperbolic sine
[Link](x) hyperbolic cosine
[Link](x) hyperbolic tangent
[Link](x) hyperbolic arcsine
[Link](x) hyperbolic arccosine
[Link](x) hyperbolic arctangent
Various functions
x**n x to the power of n, example: x**2
[Link](x) square root
[Link](x) exponential
[Link](x) natural logarithm
[Link](x) absolute value
[Link](x) sign
Useful functions for complex numbers
[Link](x) real part
[Link](x) imaginary part
[Link](x) module
[Link](x) argument in radians
[Link](x) complex conjugate
1. Introduction
The DataFrame is a data structure that organizes data in rows and columns.
which makes it a two-dimensional data structure. You can imagine it as a
5. Selection of a line
[Link] will return a single row in the form of a series when it receives a single label.
of line.
>>> [Link]['Line1']
state TX
color green
food Lamb
age 2
height 70
score 8.3
Name: Niko, dtype: object
8. Selecting a column
To select a single column of data, simply put the name of the column.
between the brackets. Let's choose the food column:
>>> df[col1]
Jane Steak
Niko Lamb
Aaron Mango
Penelope Apple
Dean Cheese
Christina Melon
Cornelia Beans
Name: col1, dtype: object
1. Introduction
Pandasis the essential library for handling data. It allows for manipulation
both the data in table form that it can retrieve or export in different
formats. It also allows for easy creation of graphs.
2. Transformation of a column
The best way to convert one or more columns of a DataFrame into values.
The goal of using pandas is to_numeric(). This function will try to change objects
non-numeric (such as strings) into integers or floating-point numbers, as appropriate.
During operations on dataframes, the names of the rows and columns are
automatically aligned:
df1 = [Link]({'A': [1, 2], 'B': [3, 4]}, index = ['a',
'c'])
df2 = [Link]({'A': [1, 2], 'C': [7, 5]}, index = ['b',
'c'])
df1 + df2give
A B C
a NaN NaN NaN
b NaN NaN NaN
c 4.0 NaN NaN
Possible operations:
df1 + df2
2 * df + 3
1 / dfelement-wise operation.
df **2square of each element.
for boolean dataframes [Link]({'A': [1, 0, 0], 'B': [0,
1, 1]}, dtype = bool):
-dfnot.
df1 & df2and.
df1 | df2or.
df1 ^ df2or exclusive.
comparison operations:df1 is equal to df2, [Link](df2), [Link](df2), df1 is less than or equal to df2,
df1 is less than df2, df1 is less than or equal to df2equality, non-equality, <, <=, >, >=. They return dataframes.
booleans.
one can also dodf1 is equal to df2, but be careful, it also returns a dataframe of booleans.
Boolean reductions:
(df > 0).all()returns a series with one element per column that is True if
all values are > 0
Any operating system that supports graphical interfaces must constantly monitor
the environment to detect events such as pressing a key on the keyboard
or on a mouse button. The operating system then informs the programs about it.
Execution course. Each program then determines whether it should respond to these events.
4. Sorting a DataFrame
Sort by values:
df.sort_values(by = 'C')returns a dataframe with the rows sorted in such a way that the
column 'C' should be in ascending order:
A BC D
a3 5.3 9 1.5 15
a1 1.1 2 3.3 4
a2 2.7 10 5.4 7
1. Data Structures
DataFrames
A DataFrame is a very important data structure in pandas. A DataFrame is
a two-dimensional table. One could even say that it is a collection of 'pandas Series'
».
[Link]([1, 2, 3])
Int64Index([1, 2, 3], dtype='int64')
5. Transformation of a column
The best way to convert one or more columns of a DataFrame into values
Numerical values are used to utilize pandas. to_numeric(). This function tries to convert objects.
non-numeric (such as strings) into integers or floating-point numbers, as appropriate.
6. Data alignment
The Pandas library is useful for performing exploratory data analysis in Python.
A pandas dataframe represents data in a tabular format. We can perform
perform operations on the data and display them. In this article, we will align the columns
on the left in Pandas. When we display the dataframe, we can align the
data in the columns on the left, the right, or the center.
import pandas as pd
df = [Link](data)
display(df)
2. Method Apply()
It is one of the main functions for playing with data and creating new variables.
returns a value after processing each row/column of a DataFrame with a
function. The function can be a default function or user-defined.
For example, here, apply can be used to find the missing values of each row and
column :
print([Link](num_missing, axis=0)) #axis=0 defines that the function will be applied correctly
on each column
Then apply for each line:
Missing values by row:
print([Link](num_missing, axis=1).head()) #axis=1 defines that the function will be properly
applied to each line
1. Introduction
On this page, we present two syntaxes: the 'PyLab' syntax which is close to that
of Matlab and the 'standard' syntax that is recommended in the new versions of
matplotlib.
For the "standard" syntax, you need to import the numpy package and the pyplot module from
matplotlib. We must then specify the libraries when calling the functions. For in
to learn more about the concept of importation, you can consult the pageModules and
imports.
2. Creation of a curve
The instruction plot()allows to draw curves that connect points whose abscissas and
Coordinates are provided in tables.
import numpy as np
import [Link] as plt
x = [Link]([1, 3, 4, 6])
y = [Link]([2, 3, 5, 1])
[Link](x, y)
[Link]()
It is possible to independently set the domains of the abscissas and ordinates using
the functionsxlim()andylim()
xlim(xmin, xmax)
ylim(ymin, ymax)
Example1 :
import numpy as np
import [Link] as plt
[Link]()
4. Adding a title
[Link]()
5. Adding a caption
import numpy as np
import [Link] as plt
[Link]()
import numpy as np
import [Link] as plt
[Link]()
To display multiple curves on the same graph, one can proceed as follows:
import numpy as np
import [Link] as plt
[Link]()
largeur_barre = 0.8
y1 = [2,8,9,7]
y2 = [5,9,4,2]
x = range(len(y1)) # position in the x-axis of the bars
Trace
[Link](x, y1, width = bar_width, color = "#3ED8C9")
[Link](x, y2, width = bar_width, bottom = y1, color =
#EDFF91
[Link](range(len(y1)), ['A', 'B', 'C', 'D']) ; [Link]()
you :
Sans_engrais = [13,15,10]
Avec_engrais = [14,10,11]
import pandas as pd
mydata = [Link]({"Sans engrais":Sans_engrais,"Avec
fertilizer: With_fertilizer
[Link] = ["A","B","C"]
from pandas import plotting
This function creates
automatically a grouped bar chart from a
dataframe (rot : label orientation)
[Link]()
1. Histograms
2. Box plots
BIBLIOGRAPHY :
Fabio Nelli Python Data Analytics Data Analysis and Science Using Pandas, matplotlib, and
the Python Programming Language
Learn data analysis with Python by Nebra Site du zero, 2012