0% found this document useful (0 votes)
31 views384 pages

Python for Machine Learning

Uploaded by

jiyeb63261
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
31 views384 pages

Python for Machine Learning

Uploaded by

jiyeb63261
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 384

Python for Machine Learning – 1

Introduction to Python
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Introduction
• Created by Guido van Rossum in 1991
• Works on different platforms (Windows, Mac,
Linux, Raspberry Pi, etc)
• Python has a simple syntax similar to the
English language
• Runs on an interpreter system
– code can be executed as soon as it is written.
– prototyping can be very quick.
• Python can be treated in a procedural way, an
object-oriented way or a functional way.
Python Installation
• Python Install
– To check if you have python installed on a Windows
PC, search in the start bar
– To check if you have python installed on a Linux or
Mac, then on linux open the command line or on Mac
open the Terminal and type:
python --version
• If you find that you do not have python installed
on your computer, then visit
https://www.python.org/
How to use Python?
• Interactive shell
• IDLE
• Editors
• Online (colab, kaggle etc.)
Running code in the interactive shell
• Python expressions and statements can be run
in the interactive shell
• Launch IDLE
• Examples
– 35 + 32
– "hello world "
– name = "Abin Thomas "
– " Hi, How are you? " + name
– print ('Hi, How are you?')
– print ("hi, how are you", name)
Input, Processing and Output
• Interactive shell – Keyboard and terminal
• print (<expression>)
• print ('Hi, How are you?')
• print (<expression>, ... , <expression>)
• print (<expression>, end=“”)
Input
• <variableƒidentifier> = input (<a string prompt>)
• name = input ("Enter your name")
• name
• print (name)
• Steps
– Displays a prompt for the input
– Receives a string of keystrokes, called characters,
entered at the keyboard and returns the string to the
shell
Type Conversion
• input function always builds a string from the
user’s keystrokes
• programmer must convert them from strings to
the appropriate numeric types
• two type conversion functions – int and float
– first = int(input("Enter the first number: "))
– second = int(input("Enter the second number: "))
– print("the sum is: ", first + second)
Summary of basic functions
Reference
• Fundamentals of Python – Kenneth A Lambert,
B L Juneja
Python for Machine Learning – 2
Editing, Saving and Running a Script
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Editing, Saving and Running a Script
• To compose, edit, and save longer, more
complex programs in files
• program files or scripts
• Run within IDLE or from the operating
system’s command prompt without opening
IDLE.
Steps
• Select the option New Window from the File
menu of the shell window
• In the new window, enter Python expressions or
statements on separate lines, in the order in
which you want Python to execute them
• At any point, you may save the file by selecting
File/Save. If you do this, you should use a .py
extension
• To run this file of code as a Python script, select
Run Module from the Run menu or press the F5
key (Windows) or the Control+F5 key (Mac or
Linux)
Behind the Scenes: How Python Works
Detecting and Correcting Syntax Errors
• typographical errors when editing programs
• syntax errors
• halts execution with an error message
Exercises - 1
1. Open a Python shell, enter the following expressions, and observe the
results:
a8
b8*2
c 8 ** 2
d 8 / 12
e 8 // 12
f8/0
2. Write a Python program that prints (displays) your name, address, and
telephone number.
3. Evaluate the following code at a shell prompt: print(“Your name is”,
name). Then assign name an appropriate value, and evaluate the
statement again.
4. Open an IDLE window, and enter the program that computes the area of
a rectangle. Load the program into the shell by pressing the F5 key, and
correct any errors that occur. Test the program with different inputs by
running it at least three times.
Exercise - 1
5. Modify the program of Exercise 4 to compute the area of
a triangle. Issue the appropriate prompts for the
triangle’s base and height, and change the names of the
variables appropriately. Then, use the formula .5 * base *
height to compute the area. Test the program from an
IDLE window.
6. Write and test a program that computes the area of a
circle. This program should request a number
representing a radius as input from the user. It should use
the formula 3.14 * radius ** 2 to compute the area, and
output this result suitably labeled.
7. Write and test a program that accepts the user’s name
(as text) and age (as a number) as input. The program
should output a sentence containing the user’s name and
age.
Exercise - 1
8. Enter an input statement using the input
function at the shell prompt. When the
prompt asks you for input, enter a number.
Then, attempt to add 1 to that number,
observe the results.
9. Enter an input statement using the input
function at the shell prompt. When the
prompt asks you for input, enter your first
name, observe the results.
Reference
• Fundamentals of Python by Kenneth Lambert
Python for Machine Learning – 3
Strings, Assignment, and Comments
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Introduction
• Text Processing is the most common
application
• Use of strings
• Documentation
Data Types
• Example – On 8th Friday, I took Python class from
GEC, Thrissur
• In computer programs – type of data is important
• What operations can be done on these data?
• Data type
– Consists of a set of values and a set of operations
• Literal
– The way a value of a data type looks to a programmer
Literals examples
String Literals
• Sequence of characters enclosed in single or
double quotation marks
• Examples
– 'hello there'
– "hello there "
–""
– ''
–" "
String Literals Examples
• "I'm going to US tomorrow"
• print ( "I'm going to US tomorrow")
• print (""" this is a very long sentence
so i am printing in the next line""")
• """ this is a very long sentence
so i am printing in the next line"""
Escape Sequences
• \n is called an escape sequence
String Concatenation
• join two or more strings to form a new string
using the concatenation operator +
• Example
– "hi, " + "jacob" + " how are you"
• * operator allows you to build a string by
repeating another string a given number of
times
• Example
– " " * 10 + "i am fine"
Variables
• variable associates a name with a value
• variable name must begin with either a letter or an
underscore ( _),
• can contain any number of letters, digits, or other
underscores
• variable names are case sensitive (weight/WEIGHT)
• typically use lowercase letters (area, interestRate)
• use all uppercase letters for the names of variables
that contain values that the program never changes
– Symbolic constants (TAX_RATE, PI)
Assignment Statement
• Variables receive their initial values and can be
reset to new values with an assignment
statement
• <variable name> = <expression>
• Example
– firstName = "Bill"
– secondName = "Clinton"
– fullName = firstName + " " + secondName
– fullName
Program Comments and Docstrings
• comment is a piece of program text that the
interpreter ignores
• useful documentation to programmers
Exercise - 2
1. Let the variable x be “dog” and the variable y be
“cat”. Find the values returned by the following
operations:
a) x + y
b )“the “ + x + “ chases the “ + y
c )x * 4
2. Write a string that contains your name and
address on separate lines using embedded
newline characters. Then write the same string
literal without the newline characters.
Reference
• Fundamentals of Python by Lambert
Thank You
Python for Machine Learning – 4
Numeric Data Types and Character Sets
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Integers
• include 0, all of the positive whole numbers,
and all of the negative whole numbers
• are written without commas
• a leading negative sign indicates a negative
value
• range of integers is infinite
• –2,147,483,648 (–231) to 2,147,483,647 (231 – 1)
Floating-Point Numbers
• Real numbers
• Real numbers have infinite precision
• floating-point numbers to represent real
numbers
• –10308 to 10308 and have 16 digits of precision
• can be written using either ordinary decimal
notation or scientific notation
Floating-Point Numbers
Character Sets
• character literals look just like string literals
and are of the string type
• belong to several different character sets,
among them the ASCII set and the Unicode
set
ASCII
Character set
• ord
– Function converts characters to their numeric ASCII
codes
• char
– Function converts numeric ASCII codes to characters

– chr(ord('A') + 3)
Reference
• Fundamentals of Python – Kenneth Lambert
Thank You
Python for Machine Learning – 5
Expressions
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Expressions
• provide an easy way to perform operations on
data values to produce other data values
• an expression’s operands are evaluated
• its operator is then applied to these values to
compute the value of the expression
Arithmetic Expressions
Precedence rules
• Exponentiation has the highest precedence and is
evaluated first
• Unary negation is evaluated next, before
multiplication, division, and remainder
• Multiplication, both types of division, and remainder
are evaluated before addition and subtraction
• Addition and subtraction are evaluated before
assignment
• Operations of equal precedence are left associative
– Exception - Exponentiation and assignment operations
are right associative
• Parentheses can change the order of evaluation
Arithmetic expression examples
Arithmetic expression
• When both operands of an arithmetic expression
are of the same numeric type (int, long, or float),
the resulting value is also of that type
• When each operand is of a different type, the
resulting value is of the more general type.
– float type is more general than the int type
• quotient operator // produces an integer
quotient ( 3//4 = 0)
• the exact division operator / always produces a
float ( 3/4 = .75)
Mixed-Mode Arithmetic and Type
Conversions
• Performing calculations involving both
integers and floating-point numbers is called
mixed-mode arithmetic
• 3.14 * 3 ** 2
– 3.14 * 9.0
Type Conversion functions
Exercise - 3
1. Let x = 8 and y = 2. find the values of the following
expressions:
a) x + y * 3
b) (x + y) * 3
c) x ** y
d) x % y
e) x / 12.0
f) x // 6
2. Let x = 4.66. Find the values of the following expressions:
a) round(x)
b) int(x)
3. Assume that the variable x has the value 55. Use an
assignment statement to increment the value of x by 1.
Reference
• Fundamentals of Python by Kenneth Lambert
Thank You
Python for Machine Learning – 6
Functions and Modules
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Functions and modules
• Python includes many useful functions
• Organized in libraries of code called modules
Calling Functions: Arguments and
Return Values
• Function is a chunk of code that can be called by
name to perform a task
• Functions require arguments, that is, specific
data values, to perform their tasks
• Arguments are also known as parameters
• When a function completes its task, the function
may send a result back to the part of the program
• Process of sending a result back to another part
of a program is known as returning a value
Function examples
• round(6.5)
• abs(4 – 5)
• print(abs(4 - 5) + 3)
• Optional arguments and required arguments
• round(7.563, 2)
• help(round)
The math Module
• Functions and other resources are coded in
components called modules
– import math
– dir(math)
– math.pi
– math.sqrt(2)
– help(math.cos)
– from math import pi, sqrt
– print(pi, sqrt(2))
– from math import *
Program Format and Structure
• Start with an introductory comment stating
the author’s name, the purpose of the
program, and other relevant information
• Include statements that do the following:
– Import any modules needed by the program
– Initialize important variables, suitably commented
– Prompt the user for input data and save the input
data in variables
– Process the inputs to produce the results
– Display the results
Running a Script from a Terminal
Command Prompt
• Windows – command prompt
• Linux/mac – terminal
• python scriptName.py
Exercise - 4
1. You can calculate the surface area of a cube if
you know the length of an edge. Write a
program that takes the length of an edge (an
integer) as input and prints the cube’s surface
area as output.
2. Five Star Video rents new videos for $3.00 a
night, and oldies for $2.00 a night. Write a
program that the clerks at Five Star Video can
use to calculate the total charge for a customer’s
video rentals. The program should prompt the
user for the number of each type of video and
output the total cost.
Exercise - 4
3. Write a program that takes the radius of a sphere (a
floating-point number) as input and outputs the
sphere’s diameter, circumference, surface area, and
volume.
4. An object’s momentum is its mass multiplied by its
velocity. Write a program that accepts an object’s
mass (in kilograms) and velocity (in meters per
second) as inputs and then outputs its momentum.
5. The kinetic energy of a moving object is given by the
formula KE=(1/2)mv2, where m is the object’s mass
and v is its velocity. Modify the program you created
in exercise 4 so that it prints the object’s kinetic
energy as well as its momentum.
Exercise - 4
6. Write a program that calculates and prints the number
of minutes in a year.
7. Light travels at 3 * 108 meters per second. A light-year
is the distance a light beam travels in one year. Write a
program that calculates and displays the value of a
light-year.
8. Write a program that takes as input a number of
kilometers and prints the corresponding number of
nautical miles. Use the following approximations:
– A kilometer represents 1/10,000 of the distance between
the North Pole and the equator.
– There are 90 degrees, containing 60 minutes of arc each,
between the North Pole and the equator.
– A nautical mile is 1 minute of an arc.
Exercise - 4
9. An employee’s total weekly pay equals the
hourly wage multiplied by the total number of
regular hours plus any overtime pay. Overtime
pay equals the total overtime hours multiplied
by 1.5 times the hourly wage. Write a program
that takes as inputs the hourly wage, total
regular hours, and total overtime hours and
displays an employee’s total weekly pay
Reference
• Fundamentals of Python by Kenneth Lambert
Thank You
Python for Machine Learning – 7
Control Statements – for loop
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Control statements - loops
• Loops - repetition statements
• Repetition of the action is known as a pass or
an iteration
• 2 types
– Definite iteration – defined no: of times
– Indefinite iteration – program determines
for loop
Count controlled loop
• Loops that count through a range of numbers
are called count controlled loops
Count controlled loop
Count controlled example
Augmented assignment
Loop Errors: Off-by-One Error
• Easy to write correctly
• Only one other possible error
– loop fails to perform the expected number of
iterations
– number is typically off by one
• Error is called an off-by-one error
• incorrectly specifies the upper bound of the
loop
Reference
• Fundamentals of Python by Kenneth Lambert
Thank You
Python for Machine Learning – 8
Control Statements – for loop (part 2)
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Traversing the Contents of a Data
Sequence
• Loop actually visits each number in a
sequence of numbers generated by the range
function
Traversing the contents of a data
sequence
Specifying the Steps in the Range
• We might want a loop to skip some numbers
• list(range(1,6,1))
• list(range(1,6,2))
• list(range(1,6,3))
• Example – count of even numbers till 10
Loops That Count Down
• counting in the opposite direction
• for count in range(10,0,-1):
print(count, end=" ")
• list(range(10,0,-1))
Else part in for loop
Exercise - 5
1. Write a loop that prints your name 100 times.
Each output should begin on a new line.
2. Write a loop that prints the first 128 ASCII values
followed by the corresponding characters
3. Assume that the variable testString refers to a
string. Write a loop that prints each character in
this string, followed by its ASCII value.
4. Find the output of the following statements
print(range(10))
print(list(range(10)))
print(list(range(2, 8)))
print(list(range(2, 20, 3)))
Reference
• Introduction to Python by Kenneth Lambert
Thank You
Python for Machine Learning – 9
Selection: if and if-else Statements
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Selection
• Computer might be faced with two alternative
courses of action
• Examine or test a condition
• Selection statements
Boolean Type, Comparisons, and
Boolean Expressions
• Boolean data type
• only two data values — true and false
COMPARISON OPERATOR MEANING
== Equals
!= Not equals
< Less than
> Greater than
<= Less than or equal
>= Greater than or equal
Examples
if-else Statements
• Called a two-way selection statement
Syntax of if- else stmt
One-Way Selection Statements
Multi-Way if Statements
• Testing several conditions
• More than two alternative courses of action

Grade Marks range


A All grades above 89
B All grades above 79 and below 90
C All grades above 69 and below 80
D All grades below 70
Syntax of Multi-way if statement
Logical Operators and Compound
Boolean Expressions
Example
and, or , not
Operator precedence
Short-Circuit Evaluation
• (A and B)
– if A is false, then so is the expression
– no need to evaluate B
• (A or B)
– if A is true, then so is the expression
– no need to evaluate B
• Short-circuit evaluation
Short circuit example
Testing Selection Statements
• Make sure that all of the possible branches or
alternatives in a selection statement are
exercised
• Examine all of the conditions
• Test conditions that contain compound
Boolean expressions
Exercise - 6
1. Write a loop that counts the number of space
characters in a string. Recall that the space
character is represented as ' '
2. Assume that the variables x and y refer to
strings. Write a code segment that prints these
strings in alphabetical order
3. The variables x and y refer to numbers. Write a
code segment that prompts the user for an
arithmetic operator and prints the value
obtained by applying that operator to x and y.
Reference
• Fundamentals of Python by Kenneth Lambert
Thank you
Python for Machine Learning – 10
Conditional Iteration – while loop
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
while Loop
• for loop - number of times specified by the
programmer
• Number of iterations in a loop is unpredictable
• Loop accepts these values until the user enters
a special value or sentinel that terminates the
input
• conditional iteration
Structure and Behaviour of while Loop
• Conditional iteration - a condition be tested
within the loop
• To determine whether the loop should
continue or not
• Continuation condition
while loop
1. Evaluate the condition, yielding 0 or 1
2. If the condition is false (0), exit the while
statement and continue execution at the next
statement
3. If the condition is true (1), execute each of
the statements in the body and then go back
to step 1
• example
Count Control with a while Loop
• Example

• Count down
while Loop Examples
• Example – 1 (while)
• Example – 2 (break and continue)
• Example - 3 (random)
• Example – 4 (else)
• Example – 5 (leap year)
• Example – 6 ( largest)
• Example – 7 (prime)
• Example – 8 (factorial)
• Example – 9 (fibonacci)
Exercise - 7
1. Write a program that accepts the lengths of
three sides of a triangle as inputs. The program
output should indicate whether or not the
triangle is an equilateral triangle or right
triangle.
2. Modify the guessing-game program discussed so
that the user thinks of a number that the
computer must guess. The computer must make
no more than the minimum number of guesses.
Exercise - 7
3. The greatest common divisor of two positive integers, A
and B, is the largest number that can be evenly divided
into both of them. Euclid’s algorithm can be used to find
the greatest common divisor (GCD) of two positive
integers. You can use this algorithm in the following
manner:
– Compute the remainder of dividing the larger number by the
smaller number.
– Replace the larger number with the smaller number and the
smaller number with the remainder.
– Repeat this process until the smaller number is zero
– The larger number at this point is the GCD of A and B
– Write a program that lets the user enter two integers and
then prints each step in the process of using the Euclidean
algorithm to find their GCD.
Exercise - 7
4. Write a program that receives a series of
numbers from the user and allows the user to
press the enter key to indicate that he or she
is finished providing inputs. After the user
presses the enter key, the program should
print the sum of the numbers and their
average.
Exercise - 7
5. Write a Python code to check whether a given
year is a leap year or not.
[An year is a leap year if it’s divisible by 4 but
not divisible by 100 except for those divisible
by 400].
6. Write a Python code to print prime numbers
between an interval.
Exercise - 7
7. Write a Python program to find the factorial of a
number.
8. Write a program to display the Fibonacci
sequence up to n-th term.
A Fibonacci sequence is the integer sequence of 0,
1, 1, 2, 3, 5, 8....
The first two terms are 0 and 1.
All other terms are obtained by adding the
preceding two terms. This means to say the nth
term is the sum of (n-1)th and (n-2)th term.
Exercise - 7
9. Write a program to check if the number is an
Armstrong number or not
abcd... = an + bn + cn + dn + ...
153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is an
Armstrong number.
Reference
• Fundamentals of Python by Kenneth Lambert
Thank You
Python for Machine Learning – 11
Strings
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Introduction
• String – compound data type
• Made up of smaller pieces – characters
• String is a sequence of zero or more characters
• Immutable data structure
– internal elements can be accessed
• Substring
– portion of a string
Length of a string
• Length – number of characters it contains

h i j a c k .
0 1 2 3 4 5 6 7
Subscript Operator
Example
• name = "Steve Jobs"

S t e v e J o b s
0 1 2 3 4 5 6 7 8 9
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Example
Slicing for Substrings
• Segment of a string is called a slice

• [n:m] returns the part of the string from the


“n-eth” character to the “m-eth” character,
including the first but excluding the last
Example
Comparison
References
• Fundamentals of Python by Kenneth Lambert
• Learning with Python by Allen Downey, Jerey
Elkner, Chris Meyers
Thank you
Python for Machine Learning – 12
Testing for Substring and Number
Systems
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Testing for a substring using in
operator
Strings and Number Systems
• Decimal number system (base 10 number sys)
– 0 to 9
• Binary number system (base 2)
– 0 and 1
• Octal number system (base 8)
– 0 to 7
• Hexadecimal number system (base 16)
– 0 to 9, A, B, C, D, E, F
Number system examples
• 415
• (1100111111)2
• (637)8
• (415)10
• (19F)16
Positional system
• 635
= 6 x 102 + 3 x 101 + 5 x 100
Converting Binary to Decimal
• (110011111)2
= 1 x 28 + 1 x 27 + 0 x 26 + 0 x 25 + 1 x 24 + 1 x 23 +
1 x 22 + 1 x 2 1 + 1 x 2 0
= 256 + 128 + 0 + 0 + 16 + 8 + 4 + 2 +1
= 415
Example
Converting Decimal to Binary
• Repeated division
• Example
Other conversions
• Octal to Binary
• Binary to Octal
• Hexadecimal to Binary
• Binary to Hexadecimal
Exercise - 8
1. Write a Python script to convert the following
– Octal to Binary
– Binary to Octal
– Hexadecimal to Binary
– Binary to Hexadecimal
Reference
• Fundamentals of Python by Kenneth Lambert
Thank you
Python for Machine Learning – 13
String Methods
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Method

• Behaves like a function


• Slightly different syntax
• Method is always called with a given data
value called Object
Method
• Syntax

• dir(str)
• help(str)
String Methods
String Methods
String Methods
Reference
• Fundamentals of Python by Kenneth Lambert
Thank You
Python for Machine Learning – 14
Functions
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Function
• A block of organized, reusable code that is
used to perform a single, related action
• Provide better modularity for your application
• High degree of code reusing
Function
• Functions are not necessary
• If no function –
– Difficult to verify
– Impossible to maintain
• Humans can remember only 3 – 7 things
• Abstraction
Use of functions
• Functions Eliminate Redundancy
• Functions Hide Complexity
Use of functions
• Functions support general methods with
systematic variations
• Functions support the division of labour
Function Syntax
def FunctionName (parameters):
statement(s)
return [expression]
Defining a function
• Keyword def marks the start of function header
• Function name - to uniquely identify it
• Parameters (arguments) through which we pass
values to a function (optional)
• A colon (:) to mark the end of function header
• One or more valid python statements that make
up the function body (must have same
indentation level)
• An optional return statement to return a value
from the function
Example
Calling a Function
• Execute it by calling it from another function
or directly from the Python prompt
return Statement
• Used to exit a function and go back to the place
from where it was called
• Syntax of return
return [expression_list]
• Expression
– gets evaluated and the value is returned
• If no expression or the return statement itself is
not present
– function will return the None object
Example
Scope of variables
• Scope of a variable - the portion of a program
where the variable is recognized
• Parameters and variables defined inside a
function is not visible from outside
• Local scope
• Example
Lifetime of a variable
• Period throughout which the variable exits in
the memory
• Lifetime of variables inside a function is as
long as the function executes
• Destroyed once the function is returned
• Function does not remember the value of a
variable from its previous calls
• Example
Examples
• Example – 1 (add)
• Example – 2 (prime)
• Example – 3 (calculator)
Reference
• Fundamentals of Python by Kenneth Lambert
Thank you
Python for Machine Learning – 15
Functions – Part 2 (Function
Arguments, Higher order functions and
lambda function)

Dr. Ajay James


Asst. Professor in CSE
Government Engineering College Thrissur
Function Arguments
• Call a function by using the following types of
formal arguments
– Required arguments
– Keyword arguments
– Default arguments
– Variable-length arguments
Required arguments
• Arguments passed to a function in correct
positional order
• Number of arguments in the function call
should match exactly with the function
definition
Example – required arguments
Keyword arguments
• Caller identifies the arguments by the
parameter name
• Allows to skip arguments
• Place them out of order
Example - Keyword
Default arguments
• An argument that assumes a default value
Variable-length arguments
• To process a function for more arguments
than specified
• Called variable-length arguments
• Not named in the function definition, unlike
required and default arguments
Variable length syntax
def functionname([formal_args,] *var_args_tuple ):
statement(s)
return [expression]
• An asterisk (*) - placed before the variable name
that holds the values of all non keyword variable
arguments
• Tuple remains empty if no additional arguments
are specified during the function call
Variable length Example
lambda Function
• Anonymous - because they are not declared in the
standard manner by using the def keyword
• use the lambda keyword to create small anonymous
functions
• Lambda functions can take any number of arguments
• Return just one value in the form of an expression
• Contain commands or multiple expressions
• Cannot be a direct call to print because lambda
requires an expression
• Lambda functions have their own local namespace
• Cannot access variables other than those in their
parameter list and those in the global namespace
lambda - Syntax
• lambda [arg1 [,arg2,.....argn]]:expression
lambda examples
Higher order functions and lambda

• filter function
Higher order functions and lambda
• map function

• reduce function
References
• Fundamentals of Python by Kenneth Lambert
• https://www.programiz.com/
• https://www.tutorialspoint.com/
Thank you
Python for Machine Learning – 16
Functions – Part 3 (Recursive
Functions)

Dr. Ajay James


Asst. Professor in CSE
Government Engineering College Thrissur
Recursion
• Recursion is a way of programming or coding a
problem
• Function calls itself one or more times in its
body
Recursion Examples
• Example – 1 (factorial)
• Example – 2 (fibonacci)
• Example – 3 (sum)
• Courtesy : https://www.programiz.com/
Advantages of Recursion
• Make the code look clean and elegant
• A complex task can be broken down into
simpler sub-problems using recursion
• Sequence generation is easier with recursion
than using some nested iteration
Disadvantages of Recursion
• Sometimes the logic behind recursion is hard
to follow through
• Recursive calls are expensive (inefficient) as
they take up a lot of memory and time.
• Recursive functions are hard to debug
Exercise – 9
1. Write a Python function to check whether a
number is in a given range.
2. Write a Python function that accepts a string
and calculate the number of upper case
letters and lower case letters. (use isupper()
and islower() methods)
3. Write a Python function that takes a number
as a parameter and check the number is
prime or not.
Exercise – 9
4. Write a Python function to check whether a
number is perfect or not.
– In number theory, a perfect number is a positive
integer that is equal to the sum of its proper
positive divisors, that is, the sum of its positive
divisors excluding the number itself. Equivalently, a
perfect number is a number that is half the sum of
all of its positive divisors (including itself).
– 1 + 2 + 3 = 6 and ( 1 + 2 + 3 + 6 ) / 2 = 6
– 28 = 1 + 2 + 4 + 7 + 14 and (1 + 2 + 4 + 7 + 14+28)/2
Exercise – 9
5. Write a Python function that checks whether
a passed string is palindrome or not
6. Write a Python function to calculate the
factorial of a number using recursion
7. Write a Python function to print the fibonacci
series using recursion
References
• Fundamentals of Python by Kenneth Lambert
• https://www.programiz.com/
Thank You
Python for Machine Learning – 17
Lists – Part 1

Dr. Ajay James


Asst. Professor in CSE
Government Engineering College Thrissur
Lists
• A sequence of values
• Similar to an array in other programming
languages but more versatile
• Values in a list - items or elements
• Similar to strings (but mutable)
List Properties
• Lists are ordered
• Accessed by index
• Lists can contain any sort of object
• Lists are changeable (mutable)
List operators/functions
List operations/functions
List Methods for Inserting and
Removing Elements
Searching a list
• in operator
• index method - position
Sorting a List
• sort method
Aliasing and Side Effects
• aliases for the same object
Nested lists
• Matrices
References
• Fundamentals of Python by Kenneth Lambert
• Learning with Python by Allen Downey
• https://www.learnbyexample.org/
Thank You
Python for Machine Learning – 18
Lists – Part 2 (List comprehension)

Dr. Ajay James


Asst. Professor in CSE
Government Engineering College Thrissur
List Comprehension
• Offers a shorter syntax when you want to
create a new list based on the values of an
existing list
• Example (without list comprehension)
• Example (list comprehension)
Syntax
newlist = [expression for item in iterable if condition == True]
• Condition
– a filter that accepts only the items that evaluates to True
• Example
newlist = [x for x in names if x != "Chacko"]
newlist = [x for x in names]
• Iterable
– can be any iterable object, like a list, tuple, set etc
newlist = [x for x in range(10)]
Examples
Examples
List example programs
• Example 1 – Matrix add
• Example 2 – Matrix add using list comprehension
• Example 3 – Matrix transpose
• Example 4 – Matrix multiply
Exercise - 10
1. Write a Python program to add 2 matrices
2. Write a Python program to find the transpose
of a matrix
3. Write a Python program to multiply 2
matrices
References
• Fundamentals of Python by Kenneth Lambert
• https://www.w3schools.com/
• https://www.programiz.com/
Thank you
Python for Machine Learning – 19
Tuples – Part 1 (Create tuple,
accessing and slicing)

Dr. Ajay James


Asst. Professor in CSE
Government Engineering College Thrissur
Tuple
• A type of sequence that resembles a list
• A tuple is immutable
• Tuple literal indicated by enclosing its
elements in parentheses ()
Tuple examples
Create tuple with one element
Accessing Elements in a Tuple
• Index operator [] - access an item in a tuple
• Index starts from 0
• IndexError
• Index must be an integer (TypeError)
• Nested tuple are accessed using nested
indexing
Accessing examples
Accessing examples
Accessing nested tuple
Slicing
• A range of items in a tuple is accessed by using
the slicing operator (colon) (:)
• Changing or Deleting a Tuple
– Tuples are immutable
– Elements of a tuple cannot be changed once it has
been assigned
– If the element is itself a mutable datatype like list,
its nested items can be changed
Slicing examples
References
• Fundamentals of Python by Kenneth Lambert
• Learning with Python by Allen Downey
Thank You
Python for Machine Learning – 20
Tuples – Part 2 (Changing or Deleting a
Tuple, Operators, functions)

Dr. Ajay James


Asst. Professor in CSE
Government Engineering College Thrissur
Changing or Deleting a Tuple
• Tuples are immutable
• Elements of a tuple cannot be changed once it
has been assigned
• If the element is itself a mutable datatype like
list, its nested items can be changed
Changing a Tuple examples
Deleting a tuple
Tuple operators (+, *)
• Concatenation (+)

• Repeat (*)
Tuple Methods
• count(x)
– Return the number of items that is equal to x
• index(x)
– Return index of first item that is equal to x
Tuple operations
• In operator

• Iterating Through a Tuple


Built in functions
Function Description
Return True if all elements of the tuple are true (or if the tuple
all()
is empty).
Return True if any element of the tuple is true. If the tuple is
any()
empty, return False.

len() Return the length (the number of items) in the tuple.

max() Return the largest item in the tuple.


min() Return the smallest item in the tuple
Take elements in the tuple and return a new sorted list (does
sorted()
not sort the tuple itself).
sum() Retrun the sum of all elements in the tuple.

tuple() Convert an iterable (list, string, set, dictionary) to a tuple.


Built-in Functions examples
Tuple packing and unpacking

• Example – 1
• Example - 2
Tuple vs List
• Use tuple for heterogeneous (different)
datatypes
• Use list for homogeneous (similar) datatypes
• Iterating through tuple is faster than with list
• Tuples that contain immutable elements can
be used as key for a dictionary
• If you have data that doesn't change,
implementing it as tuple will guarantee that it
remains write-protected
References
• Fundamentals of Python by Kenneth Lambert
• https://www.geeksforgeeks.org/
• Learning with Python by Allen Downey
Thank You
Python for Machine Learning – 21
Sets, Creating, Modifying and
Removing elements

Dr. Ajay James


Asst. Professor in CSE
Government Engineering College Thrissur
Sets
• Sets are used to store multiple items in a single
variable
• Set is an unordered and unindexed collection
of items
• Every set element is unique (no duplicates)
• Set elements are immutable (cannot be
changed)
• Set itself is mutable
• Sets can be used to perform mathematical set
operations
Sets
• Can have any number of items
• May be of different types (integer, float, tuple,
string etc.)
• Set cannot have mutable elements like lists,
sets or dictionaries as its elements
Creating sets
• Using curly braces {} separated by commas
• Using built-in set() constructor
Creating sets examples
Modifying a set
• Sets are mutable
• Unordered – indexing has no meaning
• Cannot access or change an element of a set
using indexing or slicing
• Add a single element - add() method
• Multiple elements - update() method
• update() method can take tuples,
lists, strings or other sets as its argument
add() and update() methods
Removing elements from a set
• An item can be removed from a set using the
methods discard() and remove()
• Difference between the two
– discard() function leaves a set unchanged if the
element is not present in the set
– remove() function will raise an error in such a
condition (if element is not present in the set)
Removing elements example
pop() and clear() method
• Unordered – no way of determining which
item will be popped
References
• Fundamentals of Python by Kenneth Lambert
• https://www.programiz.com/
Thank You
Python for Machine Learning – 22
Set Operations, Built-in functions,
Frozen sets
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Set Operations
• Union
• Intersection
• Difference
• Symmetric difference
Union and Intersection examples
Difference and Symmetric Difference
Methods
Method Description
add() Adds an element to the set
clear() Removes all elements from the set
copy() Returns a copy of the set

difference() Returns the difference of two or more sets as a new set

difference_update() Removes all elements of another set from this set


Removes an element from the set if it is a member. (Do
discard()
nothing if the element is not in set)
intersection() Returns the intersection of two sets as a new set

intersection_update() Updates the set with the intersection of itself and another
Methods
isdisjoint() Returns True if two sets have a null intersection

issubset() Returns True if another set contains this set

issuperset() Returns True if this set contains another set

Removes and returns an arbitrary set element.


pop()
Raises KeyError if the set is empty

Removes an element from the set. If the element


remove()
is not a member, raises a KeyError
Returns the symmetric difference of two sets as a
symmetric_difference()
new set

Updates a set with the symmetric difference of


symmetric_difference_update()
itself and another

union() Returns the union of sets in a new set

Updates the set with the union of itself and


update()
others
in operator and iterating through a set
Built-in Functions
Function Description
Returns True if all elements of the set are true (or if the set
all()
is empty).
Returns True if any element of the set is true. If the set is
any()
empty, returns False.

len() Returns the length (the number of items) in the set.

max() Returns the largest item in the set.

min() Returns the smallest item in the set.

Returns a new sorted list from elements in the set(does


sorted()
not sort the set itself).

sum() Returns the sum of all elements in the set.


Frozen set
• Elements cannot be changed once assigned
References
• Fundamentals of Python by Kenneth Lambert
• https://www.programiz.com/
Thank You
Python for Machine Learning – 23
Dictionary (Creating, Accessing,
Adding, Removing)
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Dictionary
• Organizes information by association
• Dictionary associates a set of keys with data values
• Dictionaries are used to store data values in
key:value pairs
phone = { "Anton" : 8182929121, "Jose" : 9792129212}
• Dictionary is unordered, changeable and no
duplicates
• Keys – can be any immutable data (string, number
or tuple)
Creating a dictionary
• Dictionaries are written with curly brackets,
and have keys:values and separated by
comma
• dict() constructor
Creating examples
Accessing Elements
• Dictionary uses keys
• Keys can be used either inside square
brackets [] or with the get() method
• square brackets [] – KeyError is raised in case a
key is not found in the dictionary
• get() method returns None if the key is not
found
Accessing examples
Changing and Adding elements
• Dictionaries are mutable
• Can add new items or change the value of
existing items using an assignment operator
• Key is already present – existing value gets
updated
• Key is not present – a new (key: value) pair is
added to the dictionary
Changing or adding examples
Removing elements
• pop() method
– Removes an item with the provided key and returns
the value
• popitem() method
– can be used to remove and return an arbitrary (key,
value) item pair
• clear() method
– All the items can be removed
• Can also use the del keyword to remove
individual items or the entire dictionary itself
Removing elements example
Removing elements
References
• Fundamentals of Python by Kenneth Lambert
• https://www.programiz.com/
Thank you
Python for Machine Learning – 24
Dictionary Part 2(Methods, Built-in
functions and Reverse lookup)
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Methods
Method Description
clear() Removes all items from the dictionary
copy() Returns a shallow copy of the dictionary
Returns a new dictionary with keys from seq
fromkeys(seq[, v])
and value equal to v (defaults to None)
Returns the value of the key. If the key does
get(key[,d])
not exist, returns d (defaults to None)
Return a new object of the dictionary's items in
items()
(key, value) format
keys() Returns a new object of the dictionary's keys
Methods
Removes the item with the key and returns its
value or d if key is not found. If d is not
pop(key[,d])
provided and the key is not found, it raises
KeyError.
Removes and returns an arbitrary item (key,
popitem() value). Raises KeyError if the dictionary is
empty.

Returns the corresponding value if the key is in


setdefault(key[,d]) the dictionary. If not, inserts the key with a
value of d and returns d (defaults to None).

Updates the dictionary with the key/value pairs


update([other])
from other, overwriting existing keys.

values() Returns a new object of the dictionary's values


Dictionary Comprehension
• consists of an expression pair (key: value)
followed by a for statement inside curly braces
{}
Membership test using in
Iterating Through a Dictionary
Dictionary Built-in Functions
Function Description
Return True if all keys of the dictionary are
all()
True (or if the dictionary is empty).
Return True if any key of the dictionary is
any()
true. If the dictionary is empty, return False.
Return the length (the number of items) in
len()
the dictionary.
Return a new sorted list of keys in the
sorted()
dictionary.
Reverse lookup
Exercise – 12
1. Write a Python script to sort (ascending and
descending) a dictionary by value
2. Write a Python script to concatenate 2
dictionaries to create a new one
3. Write a Python script to check whether a
given key already exists in a dictionary
4. Write a Python script to generate and print a
dictionary that contains a number (between
1 and n) in the form (x, x*x)
Exercise – 12
5. Write a Python program to multiply all the
items in a dictionary
6. Write a Python program to remove a key
from a dictionary
7. Write a Python program to sort a dictionary
by key
8. Write a Python program to get the sum of all
values, the 3 highest values and the 3 lowest
values in a dictionary
Exercise – 12
9. Write a Python program to convert a list into a nested
dictionary of keys
10. Write a Python program to create a dictionary of keys
x, y, and z where each key has as value a list from 11-
20, 21-30, and 31-40 respectively. Access the fifth value
of each key from the dictionary.

{'x': [11, 12, 13, 14, 15, 16, 17, 18, 19],
'y': [21, 22, 23, 24, 25, 26, 27, 28, 29],
'z': [31, 32, 33, 34, 35, 36, 37, 38, 39]}
15
25
35
References
• Fundamentals of Python by Kenneth Lambert
• https://www.programiz.com/
Thank you
Python for Machine Learning – 25
Object Oriented Programming -1

Dr. Ajay James


Asst. Professor in CSE
Government Engineering College Thrissur
Introduction
• Procedure oriented programming - functions
• Object oriented programming – objects
• Object is a collection of data (variables) and
methods (functions) that act on those data
• Class is a blueprint for the object
• Object is also called an instance of a class
• Process of creating this object is called
instantiation
Class Definition
Class
• Tree-like class hierarchy
• At the top, or root, of this tree is the most
abstract class, named object, which is built in
• Each class immediately below another class in
the hierarchy is referred to as a subclass
• Class immediately above it, if there is one, is
called its parent class
• Example
Student interface
Example
Docstrings
• help(Student)
Docstrings
Method Definition
• s.getscore(5)
__init__ Method
Instance Variables
• Attributes of an object are represented as instance
variables
• Each individual object has its own set of instance
variables
• These variables serve as storage for its state
• Scope of an instance variable (including self) is the
entire class definition
• All of the class’s methods can refer the instance
variables
• Lifetime of an instance variable is the lifetime of the
enclosing object
• Names of instance variables must begin with self
– self._name and self._scores
__str__ Method
• Builds and returns a string representation of
an object’s state
• str(s)
• s.__str__()
• print(s)
Accessors and Mutators
• Methods that allow a user to observe but not
change the state of an object are called
accessors
• Methods that allow a user to modify an
object’s state are called mutators
• Example
Lifetime of Objects
• As long as any of the references survives, the
Student object can remain alive
• Garbage collection
Rules of Thumb for Defining a Simple
Class
1. Think about the behavior and attributes of the objects
of the new class
2. Choose an appropriate class name, and develop a
short list of the methods available to users
3. Write a short script that appears to use the new class
in an appropriate way
4. Choose the appropriate data structures to represent
the attributes of the class
5. Fill in the class template with a constructor ( __init__
method) and an __str__ method
6. Complete and test the remaining methods
incrementally
7. Document your code
References
• Fundamentals of Python By Kenneth Lambert
Thank You
Python for Machine Learning – 26
Object Oriented Programming -2
Inheritance and Types of Inheritance
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Class, Object, Constructor
• Example
Inheritance
• Capability of one class to derive or inherit the
properties from another class.
Benefits
• It represents real-world relationships well
• It provides reusability of a code
• It is transitive in nature
– which means that if class B inherits from another
class A, then all the subclasses of B would
automatically inherit from class A
Inheritance example
• Example 1
Types of inheritances
Simple Inheritance
• Example
Multiple Inheritance
• Example
Multilevel inheritance
• Example
Hierarchical inheritance
• Example
Hybrid inheritance
• Example
References
• www.geeksforgeeks.org
• www.programiz.com
Thank you
Python for Machine Learning – 27
Object Oriented Programming – 3
Polymorphism
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Polymorphism
• Taken from the Greek words Poly (many) and
morphism (forms)
• Use of a single type entity (method, operator
or object) to represent different types in
different scenarios
Function polymorphism
Polymorphism with a function and
objects
• Example
Class Polymorphism
• Python allows different classes to have
methods with the same name
• Example – 1
• Example – 2
Polymorphism and Inheritance
• We can define methods in the child class that
have the same name as the methods in the
parent class
• In inheritance, the child class inherits the
methods from the parent class
• We can modify a method in a child class which
was inherited from the parent class
• Process of re-implementing a method in the
child class is known as Method Overriding
Method overriding
• Example – 1
• Example – 2
References
• www.geeksforgeeks.org
• www.programiz.com
Thank You
Python for Machine Learning – 28
Object Oriented Programming – 4
Data Encapsulation and Data Hiding
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Data Encapsulation
• Idea of wrapping data and the methods that work
on data within one unit
• Puts restrictions on accessing variables and
methods directly
• Can prevent the accidental modification of data
• To prevent accidental change, an object’s variable
can only be changed by an object’s method
• Variables are known as private variable
• Class is an example of encapsulation
Protected members
• Protected members (in C++ and JAVA) are
those members of the class that cannot be
accessed outside the class but can be accessed
from within the class and its subclasses
• In Python, prefixing the name of the member
by a single underscore “_”
• Example
Private members
• Similar to protected members
• Difference is that the class members declared
private should neither be accessed outside the
class nor by any base class
• In python there is no existence
of Private instance variables that cannot be
accessed except inside a class.
• To define a private member prefix the member
name with double underscore “__”
• Example
Setter Method
• If you want to change the value of a private
variable, a setter method is used
• A method that sets the value of a private
variable
• Example
How to access Private variable?
• objectName._className__attributeName
• Example
References
• www.geeksforgeeks.org
• https://pythonspot.com/
Thank You
Python for Machine Learning – 29
Object Oriented Programming – 5
Abstract Class
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Abstract Class
• A blueprint for other classes
• Allows you to create a set of methods that must
be created within any child classes built from the
abstract class
• A class which contains one or more abstract
methods is called an abstract class
• An abstract method is a method that has a
declaration but does not have an implementation
• When we want to provide a common interface
for different implementations of a component,
we use an abstract class.
Examples
• Example – 1
• Example – 2
• Example – 3
References
• www.geeksforgeeks.org
• https://www.python-
course.eu/python3_abstract_classes.php
Thank you
Python for Machine Learning – 30
Exception Handling

Dr. Ajay James


Asst. Professor in CSE
Government Engineering College Thrissur
Errors
• Compile time error
• Logical error
• Run time error
Run-time errors
• Exceptions
• Examples
• https://docs.python.org/3/library/exceptions.
html
User-defined exceptions
References
• www.programiz.com
Thank You
Python for Machine Learning – 31
Text Files

Dr. Ajay James


Asst. Professor in CSE
Government Engineering College Thrissur
Files
• Inbuilt functions for creating, writing and
reading files
• Two types of files can be handled in python
– text files
• Each line of text is terminated with a special character
called EOL (End of Line), which is the new line character
(‘\n’) in python by default
– binary files
• there is no terminator for a line and the data is stored
after converting it into machine understandable binary
language
File Access Modes
• Access modes govern the type of operations
possible in the opened file
• Refers to how the file will be used once its
opened
• Define the location of the File Handle in the
file
• File handle is like a cursor, which defines from
where the data has to be read or written in
the file
• 6 access modes in python
File Access Modes
• Read Only (‘r’)
– Open text file for reading
– Handle is positioned at the beginning of the file
– If the file does not exists, raises I/O error
– Default mode in which file is opened
• Read and Write (‘r+’) :
– Open the file for reading and writing.
– Handle is positioned at the beginning of the file
– Raises I/O error if the file does not exists
File Access Modes
• Write Only (‘w’)
– Open the file for writing
– For existing file, the data is truncated and over-written
– Handle is positioned at the beginning of the file
– Creates the file if the file does not exists
• Write and Read (‘w+’)
– Open the file for reading and writing
– For existing file, data is truncated and over-written.
– The handle is positioned at the beginning of the file
File Access Modes
• Append Only (‘a’)
– Open the file for writing
– File is created if it does not exist
– Handle is positioned at the end of the file
– Data written will be inserted at the end, after the
existing data
• Append and Read (‘a+’)
– Open the file for reading and writing
– File is created if it does not exist
– Handle is positioned at the end of the file
– Data being written will be inserted at the end, after
the existing data
Opening a File
• open() function
• No module is required to be imported
• Example
Closing a file
• close() function closes the file
• Frees the memory space acquired by that file
• Used at the time when the file is no longer
needed or if it is to be opened in a different
file mode
• Example
Writing to a file
• write() :
– Inserts the string str1 in a single line in the text file

• writelines() :
– For a list of string elements, each string is inserted
in the text file
– Used to insert multiple strings at a single time
Reading from a file
• read()
– Returns the read bytes in form of a string
– Reads n bytes, if no n specified, reads the entire file
• readline() :
– Reads a line of the file and returns in form of a string.
– For specified n, reads at most n bytes.
– Does not reads more than one line, even if n exceeds
the length of the line
• readlines() :
– Reads all the lines and return them as each line a
string element in a list
Appending to a file
• Example
References
• www.geeksforgeeks.org
Thank You
Python for Machine Learning – 34
sys module

Dr. Ajay James


Asst. Professor in CSE
Government Engineering College Thrissur
sys module
• A built in module in python
• Provides several functions and variables to
manipulate the python runtime environment
• import sys
exit()
• Function is used to terminate a program when
needed
• Can also be used to exit from the python
terminal
Python for Machine Learning – 35
NumPy module – Creating ndarrays

Dr. Ajay James


Asst. Professor in CSE
Government Engineering College Thrissur
What is NumPy
• Numerical Python
• Scientific computing in Python
• Python library that provides a multidimensional
array object
• Various derived objects (such as masked arrays
and matrices)
• Routines for fast operations on arrays,
• Mathematical, logical, shape manipulation,
sorting, selecting, I/O, discrete Fourier
transforms, basic linear algebra, basic statistical
operations, random simulation
NumPy
• ndarray - an efficient multidimensional array
• n-dimensional arrays of homogeneous data
types
• Mathematical functions for fast operations on
entire arrays of data without having to write
loops
• Tools for reading/writing array data to disk
and working with memory-mapped files
NumPy vs List (sequences)
• Efficient on large arrays of data
• NumPy internally stores data in a contiguous
block of memory
• NumPy arrays also use much less memory
than built-in Python sequences
• NumPy operations perform complex
computations on entire arrays without the
need for Python for loops
NumPy ndarray: A Multidimensional
Array Object
• Fast, flexible container for large datasets in
Python
• Performs mathematical operations on whole
blocks of data using similar syntax to the
equivalent operations between scalar
elements
ndarray
NumPy data types
Python for Machine Learning – 40
Pandas

Dr. Ajay James


Asst. Professor in CSE
Government Engineering College Thrissur
pandas introduction
• Contains data structures and data
manipulation tools designed to make data
cleaning and analysis fast and easy in Python
• pandas adopts significant parts of NumPy’s
style of array-based computing
• Data processing without for loops like NumPy
• Designed for working with tabular or
heterogeneous data
• Series and DataFrame
Series
• A Series is a one-dimensional array-like object
containing a sequence of values (of similar
types to NumPy types) and an associated
array of data labels, called its index
• example
DataFrame
• A DataFrame represents a rectangular table of
data and contains an ordered collection of
columns, each of which can be a different value
type (numeric, string, boolean, etc.)
• DataFrame has both a row and column index
• A dict of Series all sharing the same index
• Data is stored as one or more two-dimensional
blocks rather than a list, dict, or some other
collection of one-dimensional arrays
DataFrame
Python for Machine Learning – 41
Pandas - DataFrame

Dr. Ajay James


Asst. Professor in CSE
Government Engineering College Thrissur
DataFrame
• A DataFrame represents a rectangular table of
data and contains an ordered collection of
columns, each of which can be a different value
type (numeric, string, boolean, etc.)
• DataFrame has both a row and column index
• A dict of Series all sharing the same index
• Data is stored as one or more two-dimensional
blocks rather than a list, dict, or some other
collection of one-dimensional arrays
DataFrame
DataFrame creation
• pandas.DataFrame( data, index, columns,
dtype, copy)
Create DataFrame
• Lists
• dict
• Series
• Numpy ndarrays
• Another DataFrame

You might also like