Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.1
Lecture 2
Introductio n to Python
Scientific Packages
IKC-MH.55 Scientific Computing with Python at October 20,
2023
Dr. Cem Özdo
˘
gan
Engineering Sciences Department
˙
Izmir Kâtip Çelebi University
Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.2
Contents
1 Introduction to Python
2 Python Libraries for Data Science
NumPy
SciPy
Matplotlib
3 Programming Examples in Python
Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.3
Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.4
Introduction to Python I
Running a Computer Program.
Figure: Running a Computer Program.
Python is an interpreted language.
The cod e is pre-processed to produce a bytecode (similar to
machine language) and then executed by the interpreter
(virtua l machine).
Code portability: Runs on hardware/software platforms
different from which used to develop the code.
Python is portable if the inter preter is available on the target
platform.
Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.5
Introduction to Python II
Variables:
A variable stores a piece of data and gives it a name.
a variable name must start wi th a letter or the underscore ch aracter;
a variable name cannot start with a number;
a variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ );
white spa ce s and signs with special meanings, as "+" and "-" are not
allowed;
variable n ames are case-sensitive (age, Age and AGE are three
different variables).
Built-in data types:
Built-in data types
Text Type: str Numeric Types: int, float, complex
S equence Typ es: list, tuple, range Mapping Type: dict
S et Types: set, frozenset Boolean Type: bool
Binary Types: bytes, bytearray, memor yview
Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.6
Introduction to Python III
Vari ables:
A variable stores a piece of data and gives it a name
Lists:
What if we want to store many integers? We need a list!
Loops:
Repeat code until a conditional statement ends the loop.
Conditionals:
Sometimes you want to execute code only in certain
circumstances.
Functions:
We can separate off code into functions, that can take input
and can give output. They serve as black boxes from the
perspective of the rest of our code.
Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.7
Python Libraries for Data Science I
Extensive first an d third party libraries. Top Python Librari es for
Data Science.
NumPy (aka Numerical Python) is the core numeric and
scientific computation library in Python. General-purpose
array-processing package.
SciPy (aka Scientific Python) is extensively used for
scientific and technical computations (extends NumPy).
Matplotlib is an essential library in Python for data
visualization in data science. A plotting library.
Seaborn is another library in Python for data visualization.
Extension of Matplotlib. Statistical and graphical analysis
in data science.
Pandas (Python data analysis) is a foundational Python
library for data analysis in data science. Data cleaning,
data handling, manipulation, and modeling.
Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.8
Python Libraries for Data Science II
Top Python Libraries for Data Science.
S ciKit-Learn is a robust machine learning library in Python. Da ta
mining, feature engineering, training and deploying machine learning
models.
S tatsmodels - provides functionali ties for descriptive an d inferential
statistics for statistical models.
TensorFlow - a framework for defining an d running comp utations
that involve tensors. Ma ch ine learning and deep learning framework.
Keras is a neural network Python library for deep learni ng model
development, training, and deployment.
P yTorch - scientific computing package that uses the power of
graphics processing units.
S crapy - for web crawling frameworks.
BeautifulSoup - for web crawling and data scraping.
NLTK (Natural Language Tool Kit) is a Python package essentially
for natural language processing.
Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.9
NumPy
Numpy (Numerical Python) - T he Fundamental Package for
Scientific Computing with Python. https://numpy.org/
NumPy offers high-quality mathematical functions and
supports logical operations on built-in multi-dimensional
array objects.
NumPy arrays are significantly faster than traditional
Python lists and way more efficient in performance.
Some of the features provided by NumPy
B asic array operations such as addition and multiplicat ion
Mathematical, logical, shape manipulation operations
Indexing, slicing, flattening, and resha ping the arrays
S tacking, splitting, and broadcasting arrays
I/O Operations
Fourier transform capabilities
B asic linear algebra
B asic statistical operations
Random number g eneration
. . .
Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.10
NumPy Module Organization
Figure: NumPy Module Organizatio n.
Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.11
SciPy
SciPy is a scientific computation library in Python. A collection
of mathematical functions and algorithms built on Python’s
extension NumPy https://scipy.org/
.
It provides the user with high-level commands and classes
for manipulating and visualizing data.
It is widely used in machine learning and scientific
programming and comes with integrated support for linear
algebra and statistics.
Some of the features provided by SciPy
S earch fo r minima and maxima of functions
Calculation of function integrals
S upport for special functions
S ignal processing
Multi-dime nsional image processing
Work with genetic algorithms
Fourier transform capabilities
S olving ordinary d ifferential equations
. . .
The scipy namespace itself only contains functions
imported from numpy.
Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.12
SciPy Modules
Therefore, importing only the scipy base package does only
provide numpy content, which could be imported from numpy
directly (NOT USED as import scipy).
i.e., from scipy import linalg, io
Figure: SciPy Modules.
Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.13
Matplotlib
Matplotlib is the core plotting and data visualization package in
Python https://matplotlib.org/.
A 2D graphical Python library which produces publication
quality figures. However, it also supports 3D graphics
(mplot3d toolkit), but this is very limited.
Matplotlib is capable of producing high-quality figures in
various formats. It offers interactive cross-platform
environments for plotting.
It provides a MATLAB/Mathematica-like interface for
simple plotting pyplot submodule with sec ondary x-y axis
support, and facilitates the creation of subplots, labels,
grids, legends, use a logarithmic scale or polar
coordinates etc.
Matplotlib also allows full control of axes properties, font
styles, line and marker styles, and some more formatting
entities.
You can generate line plots (Charts) , bar charts,
histograms, power spectra, pie charts, error charts, box
plots, scatter plots, stem plots, contour plots, etc., with just
a few lines of codes in Matplotlib.
Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.14
Programming in Python I
week2_HandsOn.py:
1 # ! / usr / bin / python3
2 ######### V ari abl es #### #####
3 # Each varia b l e in python has a " type " . The variab l e type i s not
predefined , i t i s "DYNAMICALLY" resol ved at runtime
4 answer = 42 # " answer " contained an i n teger because we gave i t
5 p r i n t ( answer ) # as an i n t eger !
6 # 42
7 is _ i t _ t h u r s d a y = True # These both are booleans or t r ue / f a l s e
8 is_it_wednesday = False # values
9 pi_approx = 3.1415 # This w i l l be a f l o a t i n g po i n t number
10 my_string = " Value o f pi number " # This i s a s t r i n g datatype
11 p r i n t ( pi_approx , my_string )
12 # 3.1415 Value o f pi num ber
13 p r i n t ( " my_string [ 0 ] : " , my_string [ 0 ] ) # Access s ubstr i n g s use [ ]
14 # my_string [ 0 ] : V
15 p r i n t ( " my_string [ 1 : 5 ] : " , my_string [ 1 : 5 ] ) # or indice s
16 # my_string [ 1 : 5 ] : alue
17 # p r i n t ( pi_approx + my_string )
18 ## TypeError : unsupported operand type ( s ) f o r +: f l o a t and s t r
19 p r i n t ( my_string + " i n f our d i g i t s a f t e r . " )
20 # Value of p i nu mber i n fo u r d i g i t s a f t e r .
21 p r i n t ( type ( pi_approx ) ) # You can get the data type of any o b j ect
22 # < class f l o a t >
23 # Add iti on , s ubtra c t i on , m u l t i p l i c a t i o n , d i v i s i o n are as you
expect
24 f l o a t 1 = 5 .75; f l o a t 2 = 2.25
25 p r i n t ( f l o a t 1 + f l o a t 2 ) ; p r i n t ( f l o a t 1 f l o a t 2 ) ; p r i n t ( f l o a t 1
*
f l o a t 2 ) ; p r i n t ( f l o a t 1 / f l o a t 2 )
26 p r i n t (5 % 2) # Modulus
Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.15
Programming in Python II
1 ## More Complicated Data Types
2 # LIST . What i f we want to s t o r e many i n t e gers ? We need a l i s t .
3 p r ices = [10 , 20 , 30 , 40 , 50] # A way to define a l i s t in place
4 c o l ors = [ ] # We can also make an empty l i s t and add t o i t
5 c o l ors . append ( " Green " )
6 c o l ors . append ( " Blue " )
7 c o l ors . append ( " Red" )
8 p r i n t ( c olors )
9 p r ices . append ( " S i xty " ) # We can a lso add u n l i k e data to a l i s t
10 p r i n t ( pri c e s ) # Items i n a l i s t can be o f d i f f e r e n t type
11 p r i n t ( color s [ 0 ] ) # S ing le l i s t elements can be accessed
12 p r i n t ( color s [ 2 ] ) # w ith the o perat or [ ]
13 o u r l i s t = [ 1 , 2 , 3 , 4 , 5] # Basic L i s t Operations
14 p r i n t ( o u r l i s t + o u r l i s t ) # Concatenation
15 p r i n t (3
*
o u r l i s t ) # R e p etition
16 m u l t i p l i e d _ o u r l i s t = [ value
*
3 f o r value in o u r l i s t ] # Membership
17 p r i n t ( m u l t i p l i e d _ o u r l i s t ) # I t e r a t i o n
18 #
19 # TUPLE. A t u ple i s a sequence ordered data enclosed between ( ) .
20 tup le1 = " a " , "b" , " c " , " d "
21 tup le2 = ( physics , c hemistry , 2022 , 2023) # Data heterogeneous
22 tup le3 = (1 , 2 , 3 , 4 , 5 )
23 ikc_muh_55_info = ( " IKCMH" , " 55 " , 2023 , " February " , 28)
24 p r i n t ( " tu ple1 [ 0 ] : " , tupl e1 [ 0 ] ) # access to sing l e element
25 p r i n t ( " tu ple2 [ 1 : 5 ] : " , tup le2 [ 1 : 5 ] ) # access to s l i c e
26 p r i n t ( ikc_muh_55_info [ 0 ] + " . " + ikc_muh_55_info [ 1 ] )
27 p r i n t ( tu ple3 )
Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.16
Programming in Python III
1 # DICTIONARY . An unordered c o l l e c t i o n o f items
2 person = { "name" : " Mehmet" , " age " : 19}
3 p r i n t ( f " { person [ name ] } i s { person [ age ] } years o ld . " )
4 p r i n t ( person [ "name" ] )
5 squares = { 1 : 1 , 3: 9 , 5: 25 , 7: 49 , 9: 81}
6 for i i n squares :
7 p r i n t ( squares [ i ] )
8 #
9 ######### Loops i n Python #########
10 # Repeat code u n t i l a c o n d i t i o n a l statement ends the loop
11 # WHILE.
12 l i s t = [1 , 1 , 2 , 3 , 5 , 8]
13 p r i n t ( l i s t )
14 p r i n t ( " i " , " l i s t [ i ] " )
15 i = 0
16 while ( i < len ( l i s t ) ) : # While loops are the basic type
17 p r i n t ( i , l i s t [ i ] )
18 i = i + 1
19 #
20 # FOR. The f o r loop i s the way to w r i t e i t f a s t e r .
21 f o r i i n range (0 , len ( l i s t ) ) :
22 p r i n t ( i , l i s t [ i ] )
23 # Or you can do so even neater
24 f o r e i n l i s t :
25 p r i n t ( e )
Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.17
Programming in Python IV
1 ######### C ondit i o n als i n Python #########
2 # Sometimes you want t o execute code on ly i n c e rt a i n circumstances
3 answer = 42 # Change answer and see what code i s executed
4 i f answer == 42:
5 p r i n t ( This i s the answer t o the ultim a t e quest ion )
6 e l i f answer < 42:
7 p r i n t ( This i s l ess than the answer t o the u l timate q uesti on )
8 else :
9 p r i n t ( This i s more than the answer to the ultima t e question )
10 p r i n t ( This p r i n t statement i s run no matter what because i t i s
not indented ! )
11 # Using boolean ope rations . Question : How long does i t take me to
get to work ?
12 snowy = True
13 day = " Monday "
14 ra i n y = True
15 i f ( sn owy == False ) and ( day ! = "Monday " ) : # " and " i s boolean and .
True onl y i f both are true . False ot herwise
16 time = 7
17 e l i f ( snowy == True ) and ( day == " Monday " ) :
18 time = 11
19 e l i f ( r a i ny == True ) or ( day == " Monday " ) :
20 time = 9
21 p r i n t ( " I t takes me %d minutes " % ( time ) )
Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.18
Programming in Python V
1 # whi le & i f statements example
2 number = 23
3 running = True
4 whi le running :
5 guess = i n t ( inpu t ( Enter an integ e r : ) )
6 i f guess == number :
7 p r i n t ( Co ngratulati ons , you guessed i t . )
8 running = False # t h i s causes the whi le loop t o stop
9 e l i f guess < number :
10 p r i n t ( No, i t is a l i t t l e hi gher than t h a t . )
11 else :
12 p r i n t ( No, i t is a l i t t l e lower than t h a t . )
13 else :
14 p r i n t ( The while loop is over . )
15 p r i n t ( Done ) # Do anything e lse you want t o do here
16 #
17 ######### Functions in Python #########
18 # A f u n ction i s a block of code which onl y runs when i t i s cal l e d
and can be run r e p e t i t i v e l y .
19 # use the def keyword , and i ndent because t h i s crea tes a new block
20 def print_me ( s t r i n g ) : # Function d e f i n i t i o n i s here
21 " This p r i n t s a passed s t r i n g i n t o t h i s func t i o n " # The f i r s t
statement of a functi o n can be an o ption a l statement
22 p r i n t ( s t r i n g )
23 ret u rn # End w ith the " r eturn " keyword
24 print_me ( " I m f i r s t c a l l to user de fined func t i o n ! " ) # Function
c a l l
25 print_me ( " Again second c a l l t o the same funct i o n " ) # Function c a l l
Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.19
Programming in Python VI
1 def c h ange l i s t ( m y l i s t ) :
2 " " " This changes a passed l i s t i n t o t h i s f u n ction " " "
3 m y l i s t = [ 1 ,20 ,3 , 4 ] # Call by Value in Python . This assigns
new reference i n my l i s t
4 # C all by Reference when commenting t h i s l i n e
5 p r i n t ( " Address inside the f u nction : " , i d ( my l i s t ) )
6 m y l i s t . append (9)
7 m y l i s t [0]=7
8 m y l i s t . re move (20 )
9 p r i n t ( " Values i n s i de the func t i o n : " , my l i s t )
10 m y l i s t = [1 0 ,20 ,3 0] # Function c a l l
11 p r i n t ( " I n i t i a l values out sid e the functi o n : " , m y l i s t )
12 p r i n t ( " Address out side the func t i o n : " , i d ( m y l i s t ) )
13 cha n g elist ( m y l i s t )
14 p r i n t ( " Values o utside the functi o n : " , m y l i s t )
15 # I n i t i a l values o uts ide the f u n c tion : [10 , 20 , 30]
16 # Address outsid e the func t i o n : 140390909223488 # C a l l by Value
17 # Address inside the f u nction : 140390919434048 # Call by Value
18 # Values i n s i de the f uncti o n : [7 , 3 , 4 , 9] # C a l l by Value
19 # Values outside the f u nction : [10 , 20 , 30] # C all by Value
20 #
21 # I n i t i a l values o uts ide the f u n c tion : [ 10 , 20 , 30]
22 # Address outsid e the func t i o n : 140390919434048 # C a l l by Ref .
23 # Address inside the f u nction : 140390919434048 # Call by Ref .
24 # Values i n s i de the f uncti o n : [7 , 30 , 9 ] # C a l l by Reference
25 # Values outside the f u nction : [ 7 , 30 , 9] # C a l l by Reference
Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.20
Programming in Python VII
1 def step ( x ) : # Your f u nction s can r eturn data i f you so choose
2 i f ( x < 0) :
3 r e t urn 1
4 e l i f ( x > 0) :
5 r e t urn 1
6 p r i n t ( step ( 1) ) # c a l l func t i o ns by repeati ng t h e i r name, and
p u t t i n g your variab l e i n the p arenthesis
7 p r i n t ( step (1) ) # Your v a riabl e need not be named the same th ing ,
but i t should be the r i g h t type
8 # what happens f o r x = 0?
9 p r i n t ( step (0) ) # Python automa t i c ally adds i n a " r e t urn none "
statement i f you are missing one .
10 #
11 # Fix the ret u r n none issue
12 def step_v2 ( x ) :
13 i f ( x < 0) :
14 ret u rn 1
15 e l i f ( x >= 0) :
16 ret u rn 1
17 p r i n t ( step_v2 ( 0) )
Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.21
Programming in Python VIII
1 ######### Im porti ng i n Python #########
2 # Just about every standard mat h f u nction on a c a l c u l a t o r has a
python equ i v a l ent premade.
3 impor t math
4 f l o a t 1 = 5.75
5 f l o a t 2 = 2.25
6 p r i n t ( math . lo g ( f l o a t 1 ) ) ; p r i n t ( math . exp ( f l o a t 2 ) ) ; p r i n t ( math . pow
(2 , 5 ) )
7 p r i n t ( 2 . 0
* *
5 . 0 ) # There i s a quicker way t o w r i t e exponents
8 #
9 ######### Numpy " The Fundamental Package f o r S c i e n t i f i c
Computing wit h Python " #########
10 # numpy has arrays , which f u nction s i m i l a r l y t o Python l i s t s .
11 #
12 # Generally , i t i s used a convention on names used t o import
packages ( such as numpy , scipy , and m a t p l o t l i b )
13 # imp ort [ package ] as [ a l i a s ]
14 imp ort numpy as np
15 imp ort m a t p l o t l i b as mpl
16 imp ort m a t p l o t l i b . pyplot as p l t
17 #
18 # Generall y scipy i s not imported as module because i n t e r e s t i n g
funct i o n s in scipy are ac t u a l l y located in the submodules , so
submodules or s i n g l e f u n ctions are imported
19 # from [ package ] i mport [ module ] as [ a l i a s ]
20 from scipy i mport f f t p a c k
21 from scipy i mport i n t e g r a t e
Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.22
Programming in Python IX
1 i mport numpy as np # Here , we grab a l l of the fun c t i ons and t o o l s
from the numpy package and s t o re them i n a l o c a l v a r i able
called np .
2 l = [ 1 ,2 , 3 , 4] # python l i s t
3 p r i n t ( l )
4 l_np = np . array ( l )
5 p r i n t ( l_np )
6 p r i n t ( l
*
5) # m u l t i p l y i n g a python l i s t r e p l i c a t e s i t
7 p r i n t ( l_np
*
5) # numpy applies oper ation elementwise
8 #
9 ## 1D array
10 a1 = np . array ( [ 1 , 2 , 3 , 4 ] ) # i n i t i a l i z e d wi th a numpy l i s t . Be
c a r e f u l wi th syntax . T he parentheses and b rackets are both
requi red
11 p r i n t ( a1 )
12 p r i n t ( a1 . shape ) # shape i n dicates the rank of the arr ay
13 #
14 ## Rank 2 a rray
15 # row v ector
16 a2 = np . array ([ [ 1 , 2 , 3 ,4 ] ] )
17 p r i n t ( a2 )
18 p r i n t ( a2 . shape ) # shape i n dicates the rank of the arr ay . t h i s
looks more l i k e a row vector
19 # column vec tor
20 a3 = np . array ( [ [ 1 ] ,
21 [ 2 ] ,
22 [ 3 ] ,
23 [ 4 ] ] )
24 p r i n t ( a3 )
25 p r i n t ( a3 . shape ) # t h i s looks more l i k e a column vec tor
Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.23
Programming in Python X
1 i mport numpy as np
2 a = np . array ( [ 0 , 10 , 20 , 30 , 4 0 ] )
3 p r i n t ( a )
4 p r i n t ( a [ : ] )
5 p r i n t ( a [ 1 : 3 ] )
6 a [ 1 ] = 15
7 p r i n t ( a )
8 b = np . arange (5, 5 , 0 . 5 )
9 p r i n t ( b )
10 p r i n t ( b
* *
2 )
11 1/ b
12 # < input > : 1: divide by zero encountered i n tr u e _divide
13 1/ b [ 1 0 ]
14 # < input > : 1: divide by zero encountered i n double_scalars
15 #
16 ## Elementwise opera tions
17 a = np . array ( [ 1 , 2 , 3 ] )
18 b = np . array ( [ 9 , 8 , 7 ] )
19 p r i n t ( a )
20 p r i n t ( a . shape ) ; p r i n t ( b . shape )
21 p r i n t ( a [ 0 ] ) # Access elements from them j u s t l i k e a l i s t
22 #
23 # Elementwise opera tio ns . This i s d i f f e r e n t from MATLAB where you
add a dot to get element wise ope rator s .
24 c = a + b
25 d = a b
26 e = a
*
b
27 f = a / b
28 p r i n t ( c ) ; p r i n t ( d ) ; p r i n t ( e ) ; p r i n t ( f )
Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.24
Programming in Python XI
1 i mport numpy as np
2 # What about mu lti dimensional array s ? Matrices ! You j u s t nest
l i s t s w i t h i n l i s t s
3 A = np . array ( [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] ) ; p r i n t (A)
4 # [ [ 1 2 3]
5 # [ 4 5 6]
6 # [ 7 8 9 ] ]
7 p r i n t (A. shape )
8 # (3 , 3)
9 B = np . array ( [ [ 1 , 1 , 1 ] , [ 2 , 2 , 2 ] , [ 3 , 3 , 3 ] ] ) ; p r i n t (B)
10 C = np . m atmul (A, B) ; p r i n t (C) # The n mat rix m u l t i p l i c a t i o n
11 p r i n t ( np . l i n a l g . det (A) ) # Or determinants
12 #
13 imp ort numpy as np
14 p = np . poly1d ( [ 3 , 4 , 5 ] )
15 p r i n t ( p )
16 # 2
17 # 3 x + 4 x + 5
18 p r i n t ( p
*
p )
19 # 4 3 2
20 # 9 x + 24 x + 46 x + 40 x + 25
21 p r i n t ( p . i n t e g ( k=6) )
22 # 3 2
23 # 1 x + 2 x + 5 x + 6
24 p r i n t ( p . d e r iv ( ) )
25 # 6 x + 4
26 p ( [ 4 , 5 ] )
27 # array ( [ 69 , 100])
Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.25
Programming in Python XII
1 ##### SciPy i s a s c i e n t i f i c computation l i b r a r y i n Python ## ###
2 # A c o l l e c t i o n of f u n ctions to perform basic s c i e n t i f i c
programming and data anal y s i s
3 # I n tegra t e a l i s t of numbers using s cipy you might use a f u nction
called trapz from the i n t e g r a t e package
4 impor t scipy . i n t e g r a t e as i nteg
5 # from s cipy import i n t e g r a t e as integ
6 r e s u l t = i n teg . t r a pz ( [ 0 , 1 , 2 , 3 , 4 , 5] )
7 p r i n t ( r e s u l t )
8 # I n tegra t e s i n ( x ) from 0 to Pi you could use the quad f uncti o n
9 impor t numpy as np
10 imp ort sc ipy . i n t e g r a t e as i n t e g
11 r e s u l t = i n t e g . quad ( np . sin , 0 , np . pi )
12 p r i n t ( r e s u l t )
13 #
14 ######### M a t p l o t l i b #########
15 # M a t plotl i b , l i k e many Python packages , i s organized i n t o a
number of " modules " ( e s s en t i a l l y subsets of functi o n s ) .
16 imp ort m a t p l o t l i b . pyplot as p l t # i mport packages wi th a l i a s
17 # from m a t p l o t l i b import p y p l ot as p l t
18 x_vals = [ 2, 1, 0 , 1 , 2]
19 y_vals = [ 4, 2, 0 , 2 , 4]
20 p r i n t ( x_vals , y_vals )
21 p l t . xlabel ( abscissa ) # add a l a b e l to the x ax is
22 p l t . ylabel ( ordi n a t e ) # add a l a b e l t o the y axi s
23 p l t . t i t l e ( A p r actice p l o t ) # add a t i t l e
24 p l t . p l o t ( x_vals , y_vals , marker ="o" )
25 p l t . sa vefig ( plot_0 . png ) # save the fi g u r e to the c u r rent
d i r e t o r y as a png f i l e
26 p l t . sh ow ( )
Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.26
Programming in Python XIII
1 i mport m a t p l o t l i b . pyplot as p l t
2 impor t numpy as np
3 t = np . arange (0.0 , 2.0 , 0.0 1)
4 p r i n t ( t )
5 p r i n t ( t . shape )
6 p r i n t ( len ( t ) )
7 s = 1 + np . s i n ( 2
*
np . p i
*
t ) # Degree to Radian conversion
8 p r i n t ( s )
9 p l t . p l o t ( t , s )
10 p l t . xlabel ( Time ( s ) ) ; p l t . y l abel ( Voltage (mV) )
11 p l t . t i t l e ( Voltage vs Time )
12 p l t . g r i d ( True )
13 p l t . sa vefig ( " t e s t . png " )
14 p l t . sh ow ( )
15 #
16 # M u l t i p l o t t i n g
17 imp ort numpy as np
18 imp ort m a t p l o t l i b . pyplot as p l t
19 x1 = np . lin space ( 0 . 0 , 5.0) ; x2 = np . lin space ( 0.0 , 2.0)
20 y1 = np . cos (2
*
np . p i
*
x1 )
*
np . exp( x1 ) ; y2 = np . cos ( 2
*
np . pi
*
x2 )
21 p l t . su bplot (2 , 1 , 1) # use the subpl ot func t i o n to generate
m u l t i p l e panels w i t h i n the same p l o t t i n g window
22 p l t . p l o t ( x1 , y1 , o )
23 p l t . t i t l e ( 2 sub plots )
24 p l t . ylabel ( Damped o s c i l l a t i o n )
25 p l t . su bplot (2 , 1 , 2)
26 p l t . p l o t ( x2 , y2 , . )
27 p l t . xlabel ( time ( s ) ) ; p l t . y l a bel ( Undamped )
28 p l t . sh ow ( )
Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.27
Programming in Python XIV
1 # imp ortin g a l l f unction s from pylab module
2 from pylab i mport
*
# Not the p refer r e d methodology . Means t o
bring e veryt hin g i n to the top l e v e l name space
3 x = arange (1 , 10 , 0 . 5 ) ; p r i n t ( x )
4 xsquare = x
* *
2 ; p r i n t ( xsquare )
5 xcube = x
* *
3 ; p r i n t ( xcube )
6 xsquareroo t = x
* *
0 . 5 ; p r i n t ( xsquareroot )
7 fi g u r e (1 ) # open f i g u r e 1
8 pl o t ( x , xsquare ) # basic plo t
9 x l a bel ( abscissa ) # add a l a b e l t o the x axi s
10 ylab e l ( ordina t e ) # add a l a b e l to the y a xis
11 t i t l e ( A prac t i c e p l o t ) # add a t i t l e
12 savefig ( pl ot_1 . png ) # save the f i g u r e to the c u r rent d i r e t o r y
13 f i g u r e ( 2) # open a second f i g u r e
14 p l o t ( x , xsquare , ro ,x , xcube , g+ ) # Two p l o t s . Red c i r c l e s wi th
no l i n e . Green plus signs j o i ned by a dashed curve
15 xlab e l ( abscissa ) # x and y lab els , t i t l e
16 ylab e l ( ordina t e ) # x and y label s , t i t l e
17 t i t l e ( More p racti c e ) # x and y label s , t i t l e
18 legend ( ( squared , cubed ) ) # add a legend
19 savefig ( pl ot_2 . png ) # save the f i g u r e
20 f i g u r e ( 3) # open a t h i r d f i g u r e
21 sub plot (3 , 1 ,1) ; p l o t ( x , xsquareroot , k
*
: ) # Black s t ars+do tted l i n e
22 t i t l e ( square r o o ts ) # add a t i t l e
23 sub plot (3 , 1 ,2) ; p l o t ( x , xsquare , r> ) # Red t r i a n g l e s +dashed l i n e
24 t i t l e ( squares ) # add a t i t l e
25 sub plot (3 , 1 ,3) ; p l o t ( x , xcube , mh ) # Magenta hexagons+ s o l i d l i n e
26 t i t l e ( cubes ) # add a t i t l e
27 savefig ( pl ot_3 . png ) # save the f i g u r e
28 show ( )
Introduction to Python
Dr. Cem Özdo
˘
gan
LOGIK
Introduction to Python
Python Libraries for
Data Science
NumPy
SciPy
Matplotlib
Programming
Examples in Python
2.28
Programming in Python XV
1 ######### How to fi n d documentation #########
2 # The d i r ( module ) funct i o n can be used to l ook at the namespace of
a module or package , i . e . to f i n d out names t h a t are defined
inside the module
3 # The help ( f unctio n ) f u nction i s avail a b l e f o r each module / o b ject
and all ows t o know the documentation f o r each module or
funct i o n
4 #
5 impor t math
6 d i r ( )
7 d i r ( math . acos )
8 help ( math . acos )
9 impor t m a t p l o t l i b . p y plot
10 d i r ( m a t p l o t l i b . pyplo t )
Some links to study python.
https://python-course.eu/
https://www.codecademy.com/catalog/language/python
https://scipy-lectures.org/
https://computation.physics.utoronto.ca/tutorials/
https://moodle2.units.it/course/view.php?id=6837
https://jckantor.github.io/CBE30338/
https://matplotlib.org/stable/tutorials/index.html