Introduction To Python: Arun Kumar
Introduction To Python: Arun Kumar
Introduction To Python: Arun Kumar
Arun Kumar
IIT Ropar
1 / 41
Outline of the Talk
1 Introduction to Python
Scientific Stack
Quotes about Python
2 Working With Python
Python Containers
Conditionals/Iteration/Looping/ Functions/Modules
3 Introduction to NumPy
Solving system of linear equations
4 Introduction to Matplotlib
Scatter Plot
Plotting a histogram
5 Introduction to Pandas
Pandas Data Structures
6 Scipy
7 More Functions...
2 / 41
3 / 41
What is Python ?
5 Its designer, Guido Van Rossum took the name form BBC comedy
series Monty Pythons Flying Circus".
6 Website: http://www.python.org
4 / 41
Scientific Stack
NumPy
provides support for large, multi-dimensional arrays and matrices.
Pandas
pandas builds on NumPy and provides richer classes for the management and analysis of time
series and tabular data.
SciPy
contains modules for optimization, linear algebra, integration, interpolation, special functions, FFT,
signal and image processing, ODE solvers etc.
matplotlib
This is the most popular plotting and visualization library for Python, providing both 2D and 3D
visualization capabilities.
rpy2
The high-level interface in rpy2 is designed to facilitate the use of R by Python programmers.
5 / 41
Quotes about Python
YouTube
8 / 41
Variables and Arithmetic Expression
Remark
A variable is a way of referring to a memory location used by a computer
program. A variable is a symbolic name for this physical location.
Python is a dynamically typed language where variables names are
bound to different values, possibly of varying types, during the program
execution.
The equality sign = " should be read" or interpreted as is set to" not as
is equal to".
For x = 2, y = 2, z = 2, the id(x), id(y) and id(z) will be same.
9 / 41
Python Containers
Strings
To calculate string literals, enclose them in single, double, or triple quotes as
follows:
Example
>>> a = Hello World"; b = Python is good; c = computer says no
Lists
Lists are sequences of arbitrary objects. You create a list by enclosing values
in square brackets, as follows:
Example
>>> names = [a, b, c, d]
>>> weights = [45, 50, 70, 55]
10 / 41
Python Containers Cont...
Tuples
You create a tuple by enclosing a group of values in parentheses. Unlike lists
the content of the tuple cannot be modified after creation.
Example
>>> stock = GOOG, 100, 490.10
or by using
>>> stock = (GOOG, 100, 490.1)
Sets
A set is used to contain an unordered collection of objects. Unlike lists and
tuples, sets are unordered and cannot be indexed by numbers. Moreover set
contains unique elements.
Example
>>> s= set([1,1,2,3,4,5,3])
>>> s
set([1, 2, 3, 4, 5])
11 / 41
Python Containers Contd...
Dictionaries
A dictionary is an associative array that contains objects indexed by keys. A
dictionary can be created as follows:
Example
>>> stock = {name: GOOG, shares: 100, price: 200.10}
>>> stock[date] = 18 Nov 2017
Remark
Essentially containers are those python objects which have a __contains__
method defined.
12 / 41
Conditionals
>>> temp = 25
>>> if temp > 20 and temp<28:
print pleasant"
else:
print extreme"
>>> names = [Amitabh", "Aishwarya", "Salman", "Abhishek"]
>>> for name in names:
if name[0] in AEIOU":
print name + " starts with a vowel"
else:
print name + " starts with a consonant"
13 / 41
Iteration and Looping
The most widely used looping construct is the for statement, which is used to
iterate over a collection of item.
Example
>>> for n in [1,2,3]:
print 2 to the %d power is %d " %(n, 2**n)
2 to the 1 power is 2
2 to the 2 power is 4
2 to the 3 power is 8
Example
>>> for n in range(1,6):
print 2 to the %d power is %d " %(n, 2**n)
14 / 41
Functions and Modules
Functions
def statement is used to create a function.
Example
>>> def remainder(a,b):
q =a//b; r = a-q*b
return r
Modules
A module is a collection of classes and functions for reuse.
1 save the rem.py in the folder say C:\Users\Admin\Desktop\myModule
2 append the path of the module to sys paths list as follows:
>>> import sys
>>> sys.path.append(rC:\Users\Admin\Desktop\myModule)
3 import the module as
>>> import rem
>>> rem.remainder(10,20)
15 / 41
Python Objects and Classes
Class
Class is a group or category of things having some properties or attributes in
common and differ from others by kind, type, or quality.
Object
object is one of the instance of the class. An object can perform the methods
and can also access the attributes which are defined in the class.
16 / 41
Classes
Python Class
class Stack(object):
def __init__(self):
self.stack = [ ]
def push(self, item):
self.stack.append(item)
def pop(self):
return self.stack.pop()
def length(self):
return len(self.stack)
Remark
self represents the instance of the class. By using the "self" keyword we
can access the attributes and methods of the class in python.
"__init__" is a reserved method in python classes. It is known as a
constructor in object oriented concepts. This method called when an
object is created from the class and it allow the class to initialize the
attributes of a class. 17 / 41
18 / 41
Solving system of linear equations
x + 2y = 5
3x + 4y = 6
Example
>>> import numpy as np
>>> A = np.array([[1,2],[3,4]])
>>> b = np.array([[5],[6]])
>>> np.linalg.solve(A,b)
array([[-4. ], [ 4.5]])
19 / 41
20 / 41
Matplotlib
(a) 1a (b) 1b
(c) 1a (d) 1b
22 / 41
Scatter Plot
23 / 41
Histogram
24 / 41
Simulating 3D Brownian Motion
25 / 41
3D Brownian Motion
26 / 41
27 / 41
Pandas
Pandas helps to carry out your entire data analysis workflow in Python
without having to switch to a more domain specific language like R.
Olivier Pomel, CEO Datadog We use pandas to process time series data on our
production servers. The simplicity and elegance of its API, and its high level of performance
for high-volume datasets, made it a perfect choice for us."
28 / 41
Series and DataFrame
29 / 41
30 / 41
Binomial Distribution
Example
A company drills 10 oil exploration wells, each with a 8% chance of success.
Eight of the ten wells fail. What is the probability of that happening ?
>>> import scipy.stats
>>> x = scipy.stats.binom(n=10, p=0.08)
>>> x.pmf(2)
0.14780703546361768
Solving by Simulation
>>> N = 20000
>>> x = scipy.stats.binom(n=10, p=0.08)
>>> rns = x.rvs(N)
>>> (rns == 1).sum() / float(N)
31 / 41
Cubic Spline interpolation
32 / 41
More Functions...
33 / 41
Expectation and PMF
35 / 41
Data Download from Google, Yahoo ! Finance
1
you can check all the symbols on the page https://research.stlouisfed.org/fred2/categories/94
36 / 41
Regression Using sklearn Package
37 / 41
Option Pricing Using Binomial Model
38 / 41
Infosys Option Price
39 / 41
References
Downey, A., Elkner, J., Meyers, C. (2002). How to think like a computer
scientist. Learning with Python. Green Tea press, 2002 (Free book)
http://matplotlib.org/
http://www.numpy.org/
http://pandas.pydata.org/
https://www.python.org/
http://www.scipy.org/
40 / 41
THANK YOU!
41 / 41