Apostila2 Python
Apostila2 Python
P Y T H O N F O R A R T I F I C I A L I N T E L L I G E N C E A N D D ATA
SCIENCE
P ro f. D r. T h o m m a s K . S . F l o re s
[Link]@[Link]
Contents
1 Introduction 3
1.1 What Is Python? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Why Python for AI? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 What Is a Jupyter Notebook? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 Running Cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5 Installing Libraries (pip) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3 Control Structures 11
3.1 if / elif / else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.2 for Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.3 while Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.4 break and continue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.5 List Comprehension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
4 Functions in Python 15
4.1 Defining Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
4.2 Return Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
4.3 Advanced Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
4.4 Lambda Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Page i
Python for Artificial Intelligence CONTENTS
9 Data Cleaning 33
9.1 Detecting and Handling Missing Values . . . . . . . . . . . . . . . . . . . . . . . 33
9.2 Removing Duplicates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
9.3 Type Conversion and Normalization . . . . . . . . . . . . . . . . . . . . . . . . 34
10 Data Visualization 37
10.1 Initial Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
10.2 Line Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
10.3 Bar Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
10.4 Histogram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
10.5 Correlation Heatmap (Seaborn) . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Page ii of 49
Part I
Page 1
Chapter 1
Introduction
Python is a high-level programming language created by Guido van Rossum in 1991. Its design
philosophy prioritizes code readability and simplicity, making it ideal for both beginners and
experienced developers. Python is interpreted (no compilation step required), dynamically typed
(types are resolved at runtime), and multi-paradigm (supports procedural, object-oriented, and
functional programming styles).
• Clear and readable syntax — code often looks like English pseudocode
• Huge library ecosystem (over 400,000 packages on PyPI)
• Active community and extensive documentation
• Cross-platform: runs on Windows, Linux, and macOS
• Free and open source
Python became the dominant language for Artificial Intelligence and Machine Learning due to
a combination of practical factors:
• Specialized libraries: NumPy, Pandas, Scikit-learn, TensorFlow, PyTorch
• Simple syntax that lets you focus on algorithms rather than language details
According to the TIOBE Index (2024), Python is the #1 most popular programming
language in the world. More than 90% of Machine Learning projects use Python as their
primary language. Major companies such as Google, Meta, NASA, and Netflix use Python
in production systems.
A Jupyter Notebook is an interactive development environment that lets you combine Python
code, formatted text (Markdown), mathematical equations, and visualizations in a single doc-
Page 3
Python for Artificial Intelligence CHAPTER 1. INTRODUCTION
ument. It is widely used in Data Science and AI because it supports simultaneous experimen-
tation and documentation.
• Alt + Enter — run the cell and insert a new one below
pip is Python’s standard package manager. Use the commands below in a terminal, or directly
inside a Jupyter cell (prefix with !):
1 # Install a single library
2 pip install library_name
3
4 # Inside a Jupyter Notebook ( use ! before the command )
5 ! pip install numpy
6 ! pip install pandas matplotlib seaborn
7
8 # Check installed version
9 ! pip show numpy
10
11 # Install multiple libraries at once
12 ! pip install numpy pandas matplotlib seaborn scikit - learn
• Tip
≡ Chapter Summary
Page 4 of 49
Chapter 2
In this chapter we cover the building blocks of Python. Each concept is presented with an
explanation, practical examples, and exercises for practice.
2.1 Variables
A variable is a name that points to a value stored in memory. In Python, you do not need to
declare the type — Python infers it automatically.
1 # Creating variables in Python
2 name = ’ Maria ’ # string ( text )
3 age = 25 # integer
4 height = 1.68 # floating - point
5 student = True # boolean
6
7 # Printing values
8 print ( name ) # Output : Maria
9 print ( age ) # Output : 25
10
11 # Multiple assignment
12 x, y, z = 1, 2, 3
13 print (x , y , z ) # Output : 1 2 3
14
15 # Variable swap ( elegant Python style !)
16 x, y = y, x
17 print (x , y ) # Output : 2 1
✓ Exercise
1. Create variables to store: your name, your age, your height, and whether you wear
glasses (True/False).
2. Print all variables using print().
3. Swap the values of two numeric variables using multiple assignment.
Python has several built-in data types. The most fundamental are:
Page 5
Python for Artificial Intelligence CHAPTER 2. PYTHON LANGUAGE FUNDAMENTALS
Page 6 of 49
Python for Artificial Intelligence CHAPTER 2. PYTHON LANGUAGE FUNDAMENTALS
✓ Exercise
1. Calculate the area of a circle with radius = 7 (use pi = 3.14159).
2. Check whether 17 is odd using the % (modulo) operator.
3. Calculate the hypotenuse of a right triangle with legs 3 and 4 (use ** 0.5 for square
root).
2.4 Strings
Strings are sequences of characters. In Python they are immutable and have dozens of useful
built-in methods.
1 # Creating strings
2 first = ’ Joan ’
3 last = ’ Smith ’
4
5 # Concatenation
6 full_name = first + ’ ’ + last
7 print ( full_name ) # Joan Smith
8
9 # f - strings ( modern , recommended approach )
10 age = 30
11 msg = f ’ Hello , { first }! You are { age } years old . ’
12 print ( msg )
13
14 # Useful string methods
15 text = ’ Python is Awesome ! ’
16 print ( text . strip () ) # removes leading / trailing spaces
17 print ( text . lower () ) # all lowercase
18 print ( text . upper () ) # ALL UPPERCASE
19 print ( text . replace ( ’ Python ’ , ’ AI ’) ) # substitutes text
20
21 # Splitting and checking
22 phrase = ’ machine learning is fascinating ’
23 words = phrase . split ( ’ ’) # split by space
24 print ( words ) # [ ’ machine ’, ’ learning ’, ...]
25 print ( len ( phrase ) ) # number of characters : 33
26 print ( ’ learning ’ in phrase ) # True
27
✓ Exercise
1. Given the string ’Learning Python for AI’, extract only the word ’Python’ using
slicing.
2. Count how many times the letter ’a’ appears in the string (use the .count() method).
3. Transform the name ’ana paula’ into title case using the .title() method.
2.5 Lists
Page 7 of 49
Python for Artificial Intelligence CHAPTER 2. PYTHON LANGUAGE FUNDAMENTALS
Lists are ordered, mutable collections that can hold elements of any type. They are one of the
most commonly used data structures in Python.
1 # Creating lists
2 numbers = [1 , 2 , 3 , 4 , 5]
3 fruits = [ ’ apple ’ , ’ banana ’ , ’ orange ’]
4 mixed = [42 , ’ Python ’ , 3.14 , True ] # different types allowed
5
6 # Accessing elements ( index starts at 0)
7 print ( fruits [0]) # apple
8 print ( fruits [ -1]) # orange ( last element )
9 print ( fruits [1:3]) # [ ’ banana ’, ’ orange ’]
10
11 # Modifying lists
12 fruits . append ( ’ grape ’) # add to the end
13 fruits . insert (1 , ’ pineapple ’) # insert at position 1
14 fruits . remove ( ’ banana ’) # remove by value
15 removed = fruits . pop () # remove and return the last element
16
17 # Useful operations
18 numbers = [3 , 1 , 4 , 1 , 5 , 9 , 2 , 6]
19 print ( len ( numbers ) ) # length : 8
20 print ( min ( numbers ) ) # minimum : 1
21 print ( max ( numbers ) ) # maximum : 9
22 print ( sum ( numbers ) ) # sum : 31
23 numbers . sort () # sort in place
24 print ( numbers ) # [1 , 1 , 2 , 3 , 4 , 5 , 6 , 9]
25
26 # List of lists (2 D matrix )
27 matrix = [[1 , 2 , 3] ,
28 [4 , 5 , 6] ,
29 [7 , 8 , 9]]
30 print ( matrix [1][2]) # 6 ( row 1 , column 2)
Python lists can hold mixed types, but are slower for numerical computations. For AI/ML,
use NumPy arrays (covered in Chapter 7) — they are much faster!
✓ Exercise
1. Create a list with a student’s grades: [7.5, 8.0, 6.5, 9.0, 7.0]. Compute the
average.
2. Add a new grade (8.5) to the list and recalculate the average.
3. Sort the list of grades in descending order.
2.6 Tuples
Tuples are like lists, but immutable — once created, they cannot be modified. They are used
for data that should not change.
1 # Creating tuples
2 coordinates = (10.5 , -23.8) # lat , lon of a city
3 dimensions = (1920 , 1080) # screen resolution
4 rgb = (255 , 128 , 0) # orange in RGB
Page 8 of 49
Python for Artificial Intelligence CHAPTER 2. PYTHON LANGUAGE FUNDAMENTALS
5
6 # Accessing elements ( same as lists )
7 print ( coordinates [0]) # 10.5
8 print ( rgb [ -1]) # 0
9
10 # Attempting to modify raises an error !
11 # coordinates [0] = 5.0 # TypeError !
12
13 # Tuple unpacking
14 latitude , longitude = coordinates
15 print ( f ’ Lat : { latitude } , Lon : { longitude } ’)
16
17 # Functions that return multiple values use tuples
18 def basic_stats ( numbers ) :
19 return min ( numbers ) , max ( numbers ) , sum ( numbers ) / len ( numbers )
20
21 minimum , maximum , average = basic_stats ([3 , 7 , 2 , 9 , 5])
22 print ( f ’ Min : { minimum } , Max : { maximum } , Avg : { average } ’)
2.7 Dictionaries
Dictionaries store key-value pairs. They are extremely useful for representing real-world objects
and structured data.
1 # Creating a dictionary
2 student = {
3 ’ name ’: ’ Carlos ’ ,
4 ’ age ’: 22 ,
5 ’ major ’: ’ Data Science ’ ,
6 ’ grades ’: [8.5 , 9.0 , 7.5]
7 }
8
9 # Accessing values
10 print ( student [ ’ name ’ ]) # Carlos
11 print ( student . get ( ’ email ’ , ’N / A ’) ) # N / A ( default value )
12
13 # Adding and updating
14 student [ ’ email ’] = ’ carlos@email . com ’
15 student [ ’ age ’] = 23 # update value
16
17 # Iterating over a dictionary
18 for key , value in student . items () :
19 print ( f ’{ key }: { value } ’)
20
21 # Useful methods
22 print ( student . keys () ) # all keys
23 print ( student . values () ) # all values
24 print ( ’ name ’ in student ) # True --- checks for a key
25
Page 9 of 49
Python for Artificial Intelligence CHAPTER 2. PYTHON LANGUAGE FUNDAMENTALS
✓ Exercise
1. Create a dictionary representing a product: name, price, stock, and category.
2. Apply a 10% discount to the price and update the dictionary.
3. Check whether the key ’code’ exists in the dictionary; if not, add it with the value
’001’.
2.8 Sets
Sets are unordered collections of unique elements. They are ideal for removing duplicates and
performing set operations.
1 # Creating sets
2 fruits = { ’ apple ’ , ’ banana ’ , ’ orange ’ , ’ apple ’} # duplicate ignored
3 print ( fruits ) # { ’ apple ’, ’ banana ’, ’ orange ’}
4
5 # Creating from a list with duplicates
6 raw_grades = [7 , 8 , 7 , 9 , 8 , 10 , 7]
7 unique_grades = set ( raw_grades )
8 print ( unique_grades ) # {7 , 8 , 9 , 10}
9
10 # Set operations
11 langs_a = { ’ Python ’ , ’R ’ , ’ Julia ’}
12 langs_b = { ’ Python ’ , ’ Java ’ , ’C ++ ’}
13
14 print ( langs_a & langs_b ) # intersection : { ’ Python ’}
15 print ( langs_a | langs_b ) # union
16 print ( langs_a - langs_b ) # difference : { ’ R ’, ’ Julia ’}
≡ Chapter Summary
• Python provides four core collection types: list (ordered, mutable), tuple (ordered,
immutable), dict (key-value), set (unique elements).
• Strings are immutable sequences with dozens of built-in methods.
• Dictionaries are the go-to structure for real-world objects and ML datasets.
Page 10 of 49
Chapter 3
Control Structures
Control structures let a program make decisions and repeat actions. They form the foundation
of programming logic.
The if statement executes code conditionally. Python uses indentation (4 spaces) to define
code blocks.
1 # Basic if / elif / else structure
2 temperature = 35
3
4 if temperature > 30:
5 print ( ’ Very hot ! ’)
6 elif temperature > 20:
7 print ( ’ Pleasant temperature ’)
8 elif temperature > 10:
9 print ( ’ Cold , wear a jacket ’)
10 else :
11 print ( ’ Very low temperature ! ’)
12
13 # Compound conditions
14 grade = 7.5
15 attendance = 80
16
The for loop iterates over any sequence: list, string, range, dictionary, etc.
1 # Iterating over a list
2 algorithms = [ ’ Regression ’ , ’ Classification ’ , ’ Clustering ’]
3 for algo in algorithms :
4 print ( f ’ - { algo } ’)
5
6 # range () --- generates a sequence of numbers
7 for i in range (5) : # 0, 1, 2, 3, 4
Page 11
Python for Artificial Intelligence CHAPTER 3. CONTROL STRUCTURES
8 print (i , end = ’ ’)
9
The while loop repeats a block as long as a condition is true. Be careful to avoid infinite loops!
1 # Basic while
2 counter = 0
3 while counter < 5:
4 print ( f ’ Iteration { counter } ’)
5 counter += 1 # ESSENTIAL ! Without this : infinite loop
6
7 # Simulating algorithm convergence
8 error = 100.0
9 reduction = 0.7
10 iteration = 0
11
12 while error > 0.01: # continue until convergence
13 error = error * reduction
14 iteration += 1
15 print ( f ’ Iter { iteration }: error = { error :.4 f } ’)
16
17 print ( f ’ Converged in { iteration } iterations ! ’)
▲ Warning
Always ensure that the while loop condition will eventually become False. An infinite
loop freezes the program and requires a forced termination (Ctrl+C in the terminal or
restarting the kernel in Jupyter).
Page 12 of 49
Python for Artificial Intelligence CHAPTER 3. CONTROL STRUCTURES
An elegant and efficient syntax for creating lists from iterations. It is one of the most popular
Python features.
1 # Traditional form ( verbose )
2 squares = []
3 for n in range (10) :
4 squares . append ( n ** 2)
5
24 # Dict comprehension
25 words = [ ’ python ’ , ’ machine ’ , ’ learning ’]
26 lengths = { w : len ( w ) for w in words }
27 # { ’ python ’: 6 , ’ machine ’: 7 , ’ learning ’: 8}
✓ Exercise
1. Use list comprehension to create a list of cubes of numbers from 1 to 10.
2. Filter a list of temperatures, keeping only values above 25°C.
3. Create a dictionary mapping each number from 1 to 5 to its factorial.
Page 13 of 49
Python for Artificial Intelligence CHAPTER 3. CONTROL STRUCTURES
≡ Chapter Summary
Page 14 of 49
Chapter 4
Functions in Python
Functions are reusable blocks of code that perform a specific task. They make code more
organized, readable, and easier to maintain.
Page 15
Python for Artificial Intelligence CHAPTER 4. FUNCTIONS IN PYTHON
Lambda creates anonymous single-line functions. They are commonly used with map(), filter(),
and sorted().
1 # Basic lambda
2 square = lambda x : x ** 2
3 print ( square (5) ) # 25
4
Page 16 of 49
Python for Artificial Intelligence CHAPTER 4. FUNCTIONS IN PYTHON
14
15 # Used with map () --- applies function to each element
16 numbers = [1 , 2 , 3 , 4 , 5]
17 cubed = list ( map ( lambda x : x **3 , numbers ) )
18 print ( cubed ) # [1 , 8 , 27 , 64 , 125]
19
20 # Used with filter () --- filters elements
21 evens = list ( filter ( lambda x : x % 2 == 0 , numbers ) )
22 print ( evens ) # [2 , 4]
✓ Exercise
1. Write a function that receives a list of grades and returns each student’s status (Passed
/ Failed / Remediation).
2. Create a function using **kwargs that receives ML model characteristics and displays
them in a formatted way.
3. Use lambda + sorted() to sort a list of dictionaries by the ’salary’ field in descending
order.
≡ Chapter Summary
Page 17 of 49
Python for Artificial Intelligence CHAPTER 4. FUNCTIONS IN PYTHON
Page 18 of 49
Chapter 5
Object-Oriented Programming (OOP) organizes code into objects that combine data (attributes)
and behavior (methods). In Machine Learning, classes are used to represent models, datasets,
and pipelines.
◦ Essential Terminology
1 # Defining a class
2 class Car :
3 def __init__ ( self , make , model , year , fuel = ’ gasoline ’) :
4 self . make = make
5 self . model = model
6 self . year = year
7 self . fuel = fuel
8 self . speed = 0
9 self . running = False
10
11 def start ( self ) :
12 if not self . running :
13 self . running = True
14 print ( f ’{ self . model } started ! ’)
15 else :
16 print ( ’ The car is already running . ’)
17
Page 19
Python for Artificial Intelligence
CHAPTER 5. OBJECT-ORIENTED PROGRAMMING (CLASSES)
27
28 # Creating objects ( instances )
29 my_car = Car ( ’ Toyota ’ , ’ Corolla ’ , 2023)
30 car2 = Car ( ’ Tesla ’ , ’ Model 3 ’ , 2024 , ’ electric ’)
31
32 my_car . start ()
33 my_car . accelerate (60)
34 my_car . status ()
1 class Dataset :
2 ’ ’ ’ Represents a dataset for Machine Learning . ’ ’ ’
3
4 def __init__ ( self , name ) :
5 self . name = name
6 self . data = []
7 self . columns = []
8
9 def add_column ( self , name , values ) :
10 self . columns . append ( name )
11 if not self . data :
12 self . data = [[ v ] for v in values ]
13 else :
14 for i , v in enumerate ( values ) :
15 self . data [ i ]. append ( v )
16
17 def shape ( self ) :
18 ’ ’ ’ Returns ( rows , columns ) --- just like Pandas ! ’ ’ ’
19 return ( len ( self . data ) , len ( self . columns ) )
20
21 def head ( self , n =5) :
22 print ( f ’ Dataset : { self . name } ’)
23 print ( ’ ’. join ( self . columns ) )
24 for row in self . data [: n ]:
25 print ( ’ ’. join ( str ( v ) for v in row ) )
26
27 # Creating and using the Dataset
28 ds = Dataset ( ’ Iris Simplified ’)
29 ds . add_column ( ’ sepal_length ’ , [5.1 , 4.9 , 6.2 , 5.8])
30 ds . add_column ( ’ sepal_width ’ , [3.5 , 3.0 , 2.8 , 3.2])
31 ds . add_column ( ’ species ’ , [0 , 0 , 1 , 1])
32
33 print ( f ’ Shape : { ds . shape () } ’)
34 ds . head ()
✓ Exercise
1. Create an Employee class with attributes: name, role, salary. Add methods to give a
raise (%) and display information.
2. Create an MLModel class with attributes: name, algorithm, accuracy. Add a method to
compare two models and return the better one.
Page 20 of 49
Part II
Page 21
Chapter 6
In Artificial Intelligence, data is the fuel that powers algorithms. Before training any model,
you must collect, clean, transform, and analyze data — steps that take up roughly 70–80% of
an AI project’s total time.
Page 23
Python for Artificial Intelligence CHAPTER 6. INTRODUCTION TO DATA HANDLING
Page 24 of 49
Chapter 7
NumPy (Numerical Python) is the core library for scientific computing in Python. It provides
the ndarray (N-dimensional array) object and high-performance mathematical functions.
1 import numpy as np
2 import time
3
4 # Speed comparison : Python list vs NumPy array
5 size = 1 _000_000
6
7 # Python list
8 lst = list ( range ( size ) )
9 start = time . time ()
10 result_list = [ x * 2 for x in lst ]
11 time_list = time . time () - start
12
13 # NumPy array
14 array = np . arange ( size )
15 start = time . time ()
16 result_np = array * 2 # vectorized operation !
17 time_np = time . time () - start
18
19 print ( f ’ Python list : { time_list :.4 f } s ’)
20 print ( f ’ NumPy array : { time_np :.4 f } s ’)
21 print ( f ’ NumPy is ~{ time_list / time_np :.0 f } x faster ! ’)
1 import numpy as np
2
3 # From Python lists
4 vector = np . array ([1 , 2 , 3 , 4 , 5])
5 matrix = np . array ([[1 , 2 , 3] ,
6 [4 , 5 , 6] ,
7 [7 , 8 , 9]])
8
9 print ( vector . shape ) # (5 ,) --- 1D , 5 elements
10 print ( matrix . shape ) # (3 , 3) --- 3 rows , 3 columns
11 print ( matrix . dtype ) # int64
12 print ( matrix . ndim ) # 2 --- number of dimensions
13
14 # Special arrays --- heavily used in ML !
15 zeros = np . zeros ((3 , 4) ) # matrix of zeros
Page 25
Python for Artificial Intelligence CHAPTER 7. NUMPY — NUMERICAL COMPUTING
1 import numpy as np
2
1 import numpy as np
2
3 a = np . array ([1 , 2 , 3 , 4 , 5])
4 b = np . array ([10 , 20 , 30 , 40 , 50])
5
6 # Element - wise operations ( no loops needed !)
7 print ( a + b ) # [11 22 33 44 55]
8 print ( a * b ) # [10 40 90 160 250]
9 print ( a ** 2) # [ 1 4 9 16 25]
10 print ( np . sqrt ( a ) ) # [1. 1.41 1.73 2. 2.23]
11
12 # Statistical functions
13 data = np . random . randn (100) # 100 normal values
14 print ( f ’ Mean : { data . mean () :.4 f } ’)
15 print ( f ’ Std : { data . std () :.4 f } ’)
Page 26 of 49
Python for Artificial Intelligence CHAPTER 7. NUMPY — NUMERICAL COMPUTING
✓ Exercise
1. Create an array of 50 random values (normal distribution). Compute the mean, stan-
dard deviation, and the 25th, 50th, and 75th percentiles.
2. Create a 5×5 matrix with values from 0 to 24. Extract the main diagonal and the first
2 columns.
3. Normalize an array to the range [0, 1] using the formula: (x − min)/(max − min).
Page 27 of 49
Python for Artificial Intelligence CHAPTER 7. NUMPY — NUMERICAL COMPUTING
Page 28 of 49
Chapter 8
Pandas is the primary library for handling tabular data in Python. It provides two core data
structures: Series (1D) and DataFrame (2D — similar to a spreadsheet).
8.1 Series
1 import pandas as pd
2 import numpy as np
3
4 # Series --- 1 D array with an index
5 temps = pd . Series ([22 , 25 , 19 , 28 , 31] ,
6 index =[ ’ Mon ’ , ’ Tue ’ , ’ Wed ’ , ’ Thu ’ , ’ Fri ’ ])
7 print ( temps )
8
9 # Operations on a Series
10 print ( temps . mean () ) # mean
11 print ( temps . max () ) # maximum
12 print ( temps > 25) # boolean mask
13 print ( temps [ temps > 25]) # filtering
8.2 DataFrame
1 import pandas as pd
2
Page 29
Python for Artificial Intelligence CHAPTER 8. PANDAS — DATA MANIPULATION
1 import pandas as pd
2
3 # --- CSV ---
4 df_csv = pd . read_csv ( ’ data . csv ’) # default separator : comma
5 df_csv2 = pd . read_csv ( ’ data . csv ’ ,
6 sep = ’; ’ ,
7 encoding = ’utf -8 ’ ,
8 parse_dates =[ ’ date ’ ])
9
10 # --- TXT ( tab - separated ) ---
11 df_txt = pd . read_csv ( ’ data . txt ’ ,
12 sep = ’\ t ’ ,
13 header =0)
14
15 # --- Excel ---
16 # Requires : pip install openpyxl
17 df_excel = pd . read_excel ( ’ data . xlsx ’ ,
18 sheet_name = ’ Sheet1 ’ ,
19 header =0)
20
21 # --- Saving data ---
22 df . to_csv ( ’ output . csv ’ , index = False )
23 df . to_excel ( ’ output . xlsx ’ , index = False )
1 import pandas as pd
2
3 data = { ’ name ’: [ ’ Ana ’ , ’ Bruno ’ , ’ Carla ’ , ’ Diego ’] ,
4 ’ age ’: [25 , 30 , 28 , 35] ,
5 ’ salary ’: [4500 , 7200 , 5800 , 9100] ,
6 ’ city ’: [ ’ NY ’ , ’ LA ’ , ’ NY ’ , ’ TX ’ ]}
7
8 df = pd . DataFrame ( data )
9
10 # Selecting columns
11 print ( df [ ’ name ’ ]) # one column ( Series )
12 print ( df [[ ’ name ’ , ’ salary ’ ]]) # multiple columns
13
14 # Selection by position ( iloc ) and by label ( loc )
15 print ( df . iloc [0]) # first row
16 print ( df . iloc [1:3]) # rows 1 and 2
17 print ( df . loc [0 , ’ name ’ ]) # row 0 , column ’ name ’
18
19 # Filtering by condition
20 older = df [ df [ ’ age ’] > 28]
21 ny_employees = df [ df [ ’ city ’] == ’ NY ’]
22 senior = df [( df [ ’ salary ’] > 5000) & ( df [ ’ age ’] < 35) ]
23
24 # isin () --- check multiple values
25 eastern = df [ df [ ’ city ’ ]. isin ([ ’ NY ’ , ’ LA ’ ]) ]
26
27 # Sorting
28 df_sorted = df . sort_values ( ’ salary ’ , ascending = False )
29
Page 30 of 49
Python for Artificial Intelligence CHAPTER 8. PANDAS — DATA MANIPULATION
✓ Exercise
1. Create a DataFrame with data for 6 products (name, price, category, stock). Filter
products with stock below 10.
2. Calculate the average price per category using groupby().
3. Add a ’total_value’ column = price * stock. Sort by total value in descending order.
Page 31 of 49
Python for Artificial Intelligence CHAPTER 8. PANDAS — DATA MANIPULATION
Page 32 of 49
Chapter 9
Data Cleaning
Real-world data is rarely perfect. Missing values, duplicate records, wrong data types, and
outliers are common issues that must be addressed before training models.
1 import pandas as pd
2 import numpy as np
3
4 # Dataset with intentional problems
5 data = {
6 ’ name ’: [ ’ Alice ’ , ’ Bob ’ , None , ’ Diana ’ , ’ Eva ’] ,
7 ’ age ’: [25 , None , 30 , 28 , 35] ,
8 ’ salary ’: [4500 , 6000 , 5500 , None , 7000] ,
9 ’ city ’: [ ’ NY ’ , ’ LA ’ , ’ NY ’ , ’ NY ’ , None ] ,
10 }
11 df = pd . DataFrame ( data )
12
13 # Detecting nulls
14 print ( df . isnull () )
15 print ( df . isnull () . sum () )
16 print ( df . isnull () . mean () * 100)
17
Page 33
Python for Artificial Intelligence CHAPTER 9. DATA CLEANING
32
33 print ( df )
1 import pandas as pd
2
3 df = pd . DataFrame ({
4 ’ id ’: [1 , 2, 2, 3, 4, 4] ,
5 ’ product ’: [ ’A ’ , ’B ’ , ’B ’ , ’C ’ , ’D ’ , ’D ’] ,
6 ’ price ’: [10 , 20 , 20 , 30 , 40 , 45] # different price !
7 })
8
9 # Check for duplicates
10 print ( df . duplicated () )
11 print ( df . duplicated () . sum () )
12
13 # Remove exact duplicates
14 df_clean = df . drop_duplicates ()
15
16 # Duplicates based on specific columns ( keep first occurrence of ’ id
’)
17 df_unique = df . drop_duplicates ( subset =[ ’ id ’] , keep = ’ first ’)
18 print ( df_unique )
1 import pandas as pd
2 import numpy as np
3
4 df = pd . DataFrame ({
5 ’ date ’: [ ’ 2024 -01 -15 ’ , ’ 2024 -02 -20 ’ , ’ 2024 -03 -10 ’] ,
6 ’ price_str ’: [ ’$1 ,500.00 ’ , ’$2 ,300.50 ’ , ’ $890 .00 ’] ,
7 ’ quantity ’: [ ’ 10 ’ , ’ 25 ’ , ’7 ’] ,
8 ’ temperature ’: [36.5 , 102.0 , 37.2] # outlier !
9 })
10
11 # Type conversions
12 df [ ’ date ’] = pd . to_datetime ( df [ ’ date ’ ])
13 df [ ’ quantity ’] = pd . to_numeric ( df [ ’ quantity ’ ])
14
15 # Clean string price and convert
16 df [ ’ price ’] = ( df [ ’ price_str ’]
17 . str . replace ( ’$ ’ , ’ ’ , regex = False )
18 . str . replace ( ’ , ’ , ’ ’ , regex = False )
19 . astype ( float ) )
20
21 # Detect outliers using z - score
22 mean = df [ ’ temperature ’ ]. mean ()
23 std = df [ ’ temperature ’ ]. std ()
24 df [ ’ z_score ’] = ( df [ ’ temperature ’] - mean ) / std
25 outliers = df [ df [ ’ z_score ’ ]. abs () > 2]
26 print ( ’ Detected outliers : ’)
27 print ( outliers )
28
Page 34 of 49
Python for Artificial Intelligence CHAPTER 9. DATA CLEANING
✓ Exercise
1. Create a DataFrame with 10 rows containing at least 3 null values in different columns.
Apply a different strategy to handle each column.
2. Given a dataset with prices as strings (’$1,200.00’), convert them to float correctly.
3. Detect and remove outliers from a numeric column using the IQR (Interquartile Range)
method.
Page 35 of 49
Python for Artificial Intelligence CHAPTER 9. DATA CLEANING
Page 36 of 49
Chapter 10
Data Visualization
Visualization is essential for understanding data before building models. A good plot can reveal
patterns, outliers, and relationships that would be difficult to spot in tables.
Page 37
Python for Artificial Intelligence CHAPTER 10. DATA VISUALIZATION
10.4 Histogram
Page 38 of 49
Python for Artificial Intelligence CHAPTER 10. DATA VISUALIZATION
25 plt . tight_layout ()
26 plt . show ()
✓ Exercise
1. Create a line chart showing monthly sales over 2 years.
2. Build a 2×2 subplot grid with 4 different plot types to analyze a dataset of your choice.
3. Create a correlation heatmap for a dataset with at least 5 numeric variables.
Page 39 of 49
Python for Artificial Intelligence CHAPTER 10. DATA VISUALIZATION
Page 40 of 49
Chapter 11
AI projects often work with data beyond tables: images, audio, video, and text. This section
shows how to load each type.
1 import pandas as pd
2
Page 41
Python for Artificial Intelligence CHAPTER 11. READING DIFFERENT DATA TYPES
• Tip
In image-based AI projects, neural networks expect NumPy arrays normalized to [0, 1].
For convolutional networks (CNN), the standard input format is (batch, height, width,
channels). Always resize images to a fixed size (e.g., 224 × 224 for VGG/ResNet).
Page 42 of 49
Chapter 12
Let us put everything together! We will create a simulated student dataset and perform a
complete analysis, from data generation to visualization.
◦ Project Goal
1 import pandas as pd
2 import numpy as np
3 import matplotlib . pyplot as plt
4 import seaborn as sns
5
6 # Configuration
7 np . random . seed (42)
8 plt . style . use ( ’ seaborn - v0_8 - whitegrid ’)
9 sns . set_palette ( ’ husl ’)
10
11 # Create a synthetic student dataset
12 n = 200 # 200 students
13
14 majors = np . random . choice (
15 [ ’ Data Science ’ , ’ Engineering ’ , ’ Mathematics ’ , ’ Physics ’] , n )
16
17 study_hours = np . random . normal ( loc =5 , scale =2 , size = n ) . clip (0 ,
12)
18 sleep_hours = np . random . normal ( loc =7 , scale =1.5 , size = n ) . clip (4 ,
10)
19 absences = np . random . poisson ( lam =3 , size = n )
20
21 # Grade influenced by study hours and absences
22 raw_grade = 5 + 0.5 * study_hours - 0.2 * absences + np . random . randn
(n)
23 grade = raw_grade . clip (0 , 10) . round (1)
24
25 df = pd . DataFrame ({
26 ’ major ’: majors ,
27 ’ study_hours ’: study_hours . round (1) ,
28 ’ sleep_hours ’: sleep_hours . round (1) ,
29 ’ absences ’: absences ,
30 ’ grade ’: grade ,
Page 43
Python for Artificial Intelligence
CHAPTER 12. MINI-PROJECT — STUDENT DATASET ANALYSIS
31 })
32
1 # Statistics by major
2 print ( ’ === AVERAGE GRADE BY MAJOR === ’)
3 grade_by_major = df . groupby ( ’ major ’) [ ’ grade ’ ]. agg ([ ’ mean ’ , ’ std ’ , ’
count ’ ])
4 grade_by_major . columns = [ ’ Mean ’ , ’ Std ’ , ’ Students ’]
5 print ( grade_by_major . round (2) )
6
7 # Correlations
Page 44 of 49
Python for Artificial Intelligence
CHAPTER 12. MINI-PROJECT — STUDENT DATASET ANALYSIS
Page 45 of 49
Python for Artificial Intelligence
CHAPTER 12. MINI-PROJECT — STUDENT DATASET ANALYSIS
≡ Chapter Summary
Page 46 of 49
Chapter 13
Good code is not just code that works — it is code that others (and your future self) can
understand, maintain, and extend.
19 Returns :
20 X ( np . ndarray ) : feature matrix
21 y ( np . ndarray ) : target vector
Page 47
Python for Artificial Intelligence
CHAPTER 13. BEST PRACTICES IN PYTHON FOR DATA SCIENCE
22
23 Raises :
24 ValueError : if ’ target ’ column does not exist in the
DataFrame
25 ’’’
26 if target not in df . columns :
27 raise ValueError ( f ’ Column { target } not found ! ’)
13.3 Reproducibility
1 import numpy as np
2 import random
3
4 # ALWAYS set seeds for reproducible results !
5 SEED = 42
6 np . random . seed ( SEED )
7 random . seed ( SEED )
8
9 # For TensorFlow :
10 # import tensorflow as tf
11 # tf . random . set_seed ( SEED )
12
13 # For PyTorch :
14 # import torch
15 # torch . manual_seed ( SEED )
16
17 # Use constants for important values
18 LEARNING_RATE = 0.001
19 EPOCHS = 100
20 BATCH_SIZE = 32
21 TEST_RATIO = 0.2
Page 48 of 49
Python for Artificial Intelligence
CHAPTER 13. BEST PRACTICES IN PYTHON FOR DATA SCIENCE
• Tip
Congratulations on completing this textbook! You now have the foundations needed to advance
to the next AI/ML topics:
1. Scikit-learn — library for classical Machine Learning (Regression, Classification, Cluster-
ing)
◦ Recommended Resources
• Kaggle ([Link]) — datasets, competitions, and free courses
• [Link] — practical Deep Learning course (free)
• Google Colab — free Jupyter environment with GPU support
• Official docs: [Link], [Link], [Link]
• Hands-On Machine Learning (Aurélien Géron) — O’Reilly Media
• YouTube: 3Blue1Brown (Math), Sentdex (Python/ML), StatQuest (Statistics)
Page 49 of 49