Template [Python]
1. Data types, data structures and indexing
1.1 Basics
Object, assignment, functions, how to comment and get help
# We can use Python as a calculator!
# Built-in functions can help execute things; we usually have to provide arguments
# Don't know how a function works? Ask for help!
1.2 Data types
Numeric: integer and float
String
Boolean
Not sure?
1.3 Collections
Lists
Lists are ordered collections of changeable elements
Can we add element to a list?
List inception: list of lists
Dictionary
Dictionaries are unordered collections of changeable and indexed elements
# Dictionairies are made of keys...
# ... and values
DataFrame
DataFrames are data structures containing labeled axes
# DataFrame are not a built-in type of Python; we must import an Python library to use them
Data frames
data.frame(vector1, vector2) # bind vectors with the same length
# Df can be build from a list of lists
# Df can be build from dictionary
1.4 Dimensions
1.5 Indexing
Accessing elements of a list
Looking up values for a specific key
Getting an entire column of a DF
Int and Label indexing of DF
# integer indexing [row, col]
# label indexing [row, col]
1.6 Slicing
### PRO TIP
# Select rows with capital letters only
2. Files
Absolute paths
C:/Users/RonBumblefootThal/Documents/pythonFolder/MyFirstProject/Draft/IDon'tKnowWhatI'mDoing/etc.py
Relative Paths
~/I_love_my_project/CoolCode.py
2.1 Working directories
2.2 Save/write files
DF example
soa_tour = pd.DataFrame()
soa_tour['country'] = ['USA', 'UK', 'FRA', 'GER', 'BRA']
soa_tour['frequency'] = [39, 6, 6, 5, 3]
soa_tour['continents'] = ['north_america', 'europe', 'europe', 'europe', 'south_america']
soa_tour
# df_name.to_csv(PATH, header=BOOL)
2.3 Load/read files
From your PC
From URL
Metabolic rates data: http://sciencecomputing.io/data/metabolicrates.csv
url = "http://sciencecomputing.io/data/metabolicrates.csv"
Play around a little bit with this big DF... what can you do?
3. Control Flow
You already apply control flow when you decide how to go to work during winter.
For example:
You take the metro if it's snowy
You take the metro if it's cold
You walk every other time
Let's code it now ;)
3.1 Conditional evaluation
Simple if
statement
Structure:
if condition :
do something
Example:
If/else
statement
Structure:
if condition1 :
do something
elif condition2 :
do another thing
else :
do something else
Example:
Nested statement
if condition1 :
do something
else :
if conditionA :
do another thing
else :
do something else
Example:
Multiple conditions: AND & OR
3.2 For
loops
Using a for
loop you could plan your outings for a few days based on the forecast
What we are now familiar with:
What if we want to take into account the forecast for the next five days?
Can we still use our for
loop?
Iterations
Structure:
for i in [] :
do something for each i
Examples
# remember the len function? and how to access elements of a list?
If
statement inside for
loop
Structure:
for i in [] :
if condition on i :
do something
else :
do something else
Example:
# don't forget to correctly INDENT
3.3 Extras
Some logical operators
print (2 < 3)
print (2 > 3)
print (2 <= 2, 1 <= 2)
print (4 >= 4, 4 >= 3)
print (1 == 1)
print (1 != 1, 1 != 2)
print (not True, not False)
print (True or False, True | False)
print (True and False, True and True, False & True, False & False)
4. Functions
4.1 Syntax and arguments
Basic syntax
def function_name(args) :
result = do something with args
return result
# name and arguments
# what the function does
# what the function returns
# apply function on values
# apply function on variables
Using built-in functions
4.2 Scope
Variables can exist in a global or a local scope.
Remember, the abs_temp_difference
function is returning the value of the abs_result
variable
# what will 'abs_result' return?
Here is a second example:
# global variables
# global and local variables returned: what is what?
# which variable does not exist in the global scope?
# what is the value of 'squirrels'?
4.3 Integration
Combining functions and control flow
Let's go back to our forecast example.
Here's the forecast for an entire week:
# week forecast
weather_week = ['snowing', 'cloudy', 'snowing', 'clear', 'rainy']
temp_week = [-15, 3, -2, -23, 11]
# weekend forecast
weather_weekend = ['snowing', 'rainy']
temp_weekend = [-3, 2]
Let's build a function that will analyze either the week or the weekend forecast
def choose_transporation(weather, temperature) :
for each day :
if snowing or cold :
'Take the metro'
else :
'Walk'
# week transportation
# weekend transportation
4.4 Exercise: Animal Metabolism
This exercise will help you integrate the following:
Files handling
Control flow
Function
Write a function
to read a file if it exists and downloading it if it does not exist
# Pseudocode
function get_data(fn, url)
if fn exist
open it
else
download from url
# remember the os librairy...
path = 'data/clean/'
fn1 = 'soa_tour_python.csv'
fn2 = 'this_file_does_not_exist.csv'
print (os.path.isfile(path+fn1))
print (os.path.isfile(path+fn2))
filename = 'metabolic_rates.csv'
url = "http://sciencecomputing.io/data/metabolicrates.csv"
Extras
Default values
# Define function