Python Notes
Python Notes
VARIABLES
o Variables are connected to values (the information associated with that variable)
o Variable names can only contain letters ,numbers and underscores
STRINGS:
o Series of characters.
o Written inside quotation marks (single or double)
METHODS:
Formatting:
o F-strings: To insert a variable’s value into a string, place letter ‘f’ immediately
before opening quotation mark followed by the variable in brackets:
1. first_name = “ada”
2. last_name=”loveface”
3. full_name=f”{first_name} {last_name}”
4. print(f “Hello, {full_name}”)
1. full_name=”{} {}”.format(first_name,last_name)
Removing whitespace:
o Python can look for extra whitespace on left or right side of string:
o Right: use rstrip() method
o Left: use lstrip() method
o Both at once: strip()
NUMBERS
Integers: can be added (+), subtracted (-), multiplied (*), exponent (**) and divided (/),
following the order of operations
Floats: any number with a decimal point that follow the same operations as integers.
LISTS
F-strings:
Modifying Lists: To change an element use name of the list followed by the index of
element tot be changed and provide new value to that item:
Adding elements to a list: use the “append” method, which adds the item to the end of
the list:
1. Motorcycles.append(‘ducati’)
1. Motorcycles.insert(0, ‘ducati’)
inserting ‘ducati’ at beginning of list, shifting each other element down by one.
REMOVING ELEMENTS FROM A LIST:
o pop() method removes item in list while still allowing you to work with it above
removing:
1. First_owned = motorcycles.pop(0)
2. Print(f’The first motorcycle I owned was {first_owned}.”)
o can also use remove() method to remove from value rather than index and you
can also work with the value that’s being removed further onwards
o NOTE: remove() only removes first instance of value in the list
1. Too_expensive = ‘ducati’
2. Print(f”A {too_expensive} is too expensive for me”)
ORGANISING A LIST:
ALPHABETICALLY:
1. Motorcycles.sort()
2. Motorcycles.sort(reverse=True)
To maintain original order of a list but present it in a sorted order, you can use sorted()
function which doesn’t affect actual order of list:
1. Print(sorted(motorcycles))
1. Print(motorcycles.reverse())
1. Print(len(motorcycles))
LOOPS
For loops: used to repeat code for several elements in a list, with code in a for block
indented:
Numerical Lists: range(x,y,z) functions make it easy to generate a list of numbers where
python starts counting at x and counts up until but not including y, with z being the
increment size.
1. even_numbers = list(range(2,11,2)
2. print(even_numbers)
[2, 4, 6, 8, 10]
Statistics with a list of numbers: can find minimum, maximum and sum of numerical list
using min(), max(), sum() functions
List comprehensions: rather than using long code, allows you to complete same code in
one line
SLICING
Slicing refers to taking a certain group of elements from the list out by specifying the
index of the first and last(not including) elements you want to work with. Omitting first or
second index tells python to start from beginning or go to end respectively.
o to copy an entire list, you can slice entire list using [:], this produces two lists
rather than letting them equal each other, which does not produce a new list
Letting two lists equal to each other will produce one list even if the element appears to
only be added to one list:
1. friend_foods = my_foods
2. my_foods.append('cannoli')
3. friend_foods.append('ice cream') #adds to original list too
4. ['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
TUPLES
Tuples use parentheses rather than square brackets, are the same as lists (ordered)
however cannot be altered. Tuples can be looped through, but to write over them, you
must redefine the entire tuple:
IF STATEMENTS
If statements test for condition using equality operator (==), that if are met, run
separate code. Note: testing for equality is case sensitive.
To test if two values are not equal, test for inequality using ( !=). For numerical
comparisons, you can also use (<,>):
>>> age = 19
>>> age < 21
True
>>> age <= 21
True
>>> age > 21
False
>>> age >= 21
False
Use the keyword “and” to test if both conditions are true simultaneously, if BOTH
conditions pass as true, code will run:
1. >>> age_0 = 22
2. >>> age_1 = 18
3. >>> age_0 >= 21 and age_1 >= 21
4. False
Use the keyword “or” to test multiple conditions, however it passes if EITHER one of the
test passes (i.e. one can fail)
1. age_0 >= 21 or age_1 >= 21
2. True
Testing whether values are in/not in a list: Use the keyword “in” and “if” statements if
need be:
Boolean Expressions:
Boolean refers to conditional tests, where a Boolean value is either True or False
If-elif-else chains: allows certain code to be executed specifically when the conditional
test fails. Python only executes one block in an if-elif-else chain, skipping the rest of the
code when one passes.
1. If age , 4:
2. Print(“Your admission cost is $0”)
3. Elif age < 18:
4. Print(“your admission cost is $25”)
5. Else:
6. Print(“your admission cost is $40”)
1. if age < 4:
2. price = 0
3. elif age < 18:
4. price = 25
5. elif age < 65:
6. price = 40
7. else:
8. price = 20
9. print(f"Your admission cost is ${price}.")
Note: the else block is not required at the end of an if-elif chain. If multiple conditions
need to be tested use a series of “if” statements with no elif or else blocks, this method
is good to use when multiple conditions could be true and you want to act on every
condition that is true.
Using if statements with lists: if statements can be used to check conditions for every
element in a list:
1. Requested_toppings = []
2. If requested_toppings:
3. …..
4. Else:
5. Print(“are you sure you want a plane pizza”)
Using multiple lists: Can check if elements are in multiple lists before executing code
DICTIONARIES:
A dictionary is a collection of key-value pairs, each key is connected to a vakue and you
can use a key to access the associated value. The value could be a number, string, list or
even another dictionary. A dictionary is wrapped in curly brackets {},
To get the value associated with a key, give the name of the dictionary and then the
name of the key in square brackets:
1. print(alien_0[‘color’])
Give name of dictionary followed by new key in square brackets along with new value:
1. alien_0[‘x_position’] = 0
2. alien_0[‘y_position’] = 25
Note: changing values associated with keys can be done through the same method.
1. del alien_0[‘pionts’]
Get() method:
For dictionaries, you can use the get() method to set a default value that will be returned
if the requested key doesn’t exist, where first argument is key requested, and second is
returned value if it doesn’t exist. Note: if second argument is left blank, python will return
NONE
Looping through all the keys: use keys() method when you don’t need to work with the
values:
Note: looping through keys is the default behaviour for looping through a dictionary so
this has the same output as:
Duplicates:
when looping through a large dictionary with repeats in values, you can wrap set()
around the list wjich identifies unique items in list and builds a set from it:
Sets are unordered, unchangeable but mutable an ddo not allow duplicates ({}) (insert
or remove by add() or remove())
Nesting:
A list of dictionaries:
A list in a dictionary:
1. favorite_languages = {
2. 'jen': ['python', 'ruby'],
3. 'sarah': ['c'],
4. 'edward': ['ruby', 'go'],
5. 'phil': ['python', 'haskell'],
6. }
7. for name, languages in favorite_languages.items():
8. print(f"\n{name.title()}'s favorite languages are:")
9. for language in languages:
10. print(f"\t{language.title()}")
1. users = {
2. 'aeinstein': {
3. 'first': 'albert',
'last': 'einstein',
7. 'location': 'princeton',
8. },
9. 'mcurie': {
10. 'first': 'marie',
11. 'last': 'curie',
12. 'location': 'paris',
13. },
14. }
15. for username, user_info in users.items():
16. print(f"\nUsername: {username}")
17. full_name = f"{user_info['first']} {user_info['last']}"
18. location = user_info['location']
19.
print(f"\tFull name: {full_name.title()}")
20. print(f"\tLocation: {location.title()}")
21.
Or dictionary[key1][key2]
USER INPUTS
The input() function pauses the program and waits for user to enter some text. Once
python receives it, it assigns the input to a variable:
1. prompt = “If you tell us who you are, we can personlaise the messages you see.”
2. prompt += “\nWhat is your first name?”
3. name=input(prompt)
4. print(f\Hello, {name}!”)
Note: the input() function interprets the input as a string therefore to convert it into a
numerical value, wrap it with int() function
WHILE LOOPS
While for loops take collection of items and executes a block of code once for each item
in a collection, while loops run as long as a certain condition is true:
1. current_number = 1
2. while current_number <=5:
3. print(current_number)
4. current_number +=1
To exit a while loop immediately without running any remaining code in the loop
regardless of any conditional test use the “break” statement:
Using continue in a loop: returns to the beginning of a loop based on the result of a
conditional test, essentially getting the loop to skip that value:
1. current_number = 0
2. while current_number <10:
3. current_number +=1
4. If current_number % 2 == 0:
5. Continue
6.
7. Print(current_number)
To modify a list in a loop use a while loop rather than a for loop .
Not the while loop runs as long as the list is not empty.
Removing all instances of a specific value in a list: Use the remove() (which removes first
instance of value) within a while loop,
1. Responses ={}
2. While True:
3. Name = input(“\nWhat is your name? “
4. Response = input(“Which mountain would you like to climb one day? “)
5.
6. Responses[name]=response
7.
8. Repeat = input(“Would anyone else like to take the poll? “)
9. If repeat == “no”:
10. Break
11. Print(“\n---Polling Results---“)
12. For name, response in responses:
13. Print(f”{name} would like to climb {response}.”)
FUNCTIONS
To define a function, use “def” statement followed by function name and if applicable,
the information the function needs in parentheses. The function is not executed until it is
called upon which is done by writing name of function with parentheses that hold any
necessary information.
1. Def greet_user(username):
2. Print(f”Hello {username}!”)
3. greet_user(“jesse”)
Multiple arguments:
Python matches each argument in the function call with a parameter in the function
definition by the order of the arguments provided. To bypass this arguments can be
assigned to values where then order is irrelevant. Default values can also be assigned to
the parameters in the case an argument is not provided in the function call
1. describe_pet(‘harry’, ‘hamster’)
2. describe_pet(pet_name='harry', animal_type='hamster')
3. describe_pet(animal_type='hamster', pet_name='harry')
Return Values:
A function doesn’t have to display its output directly, instead it can process some data
and return a value or set of values, called the return value. The return statement takes a
value from inside a function and sends it back to the line that called the function.
Returning a dictionary:
Optional arguments: Use the None parameter a place holder for an optional argument
which evaluates to false in conditional tests:
Passing a list to a function can allow python to run the function on each element in the
list individually :
1. def greet_users(names):
2. for name in names:
3. Msg= f”Hello, {name.title}!”)
4. print(msg)
5.
6. usernames = [“hannah”, ‘ty’, ‘margot’ ]
7. greet_users(usernames)
To prevent a function from permanently modifying a list you can pass a copy of the list to
the function through function_name(list_name[:])
Using an asterisk before a parameter tells python to make an empty tuple and pack
whatever arguments it receives into this tuple. (pg. 147) To mix positional and arbitrary
arguments, the arbitar parameter must be placed last in the function definition so python
can match the positional and keyword arguments first and then collect any remaining
arguments in the remaining parameter. Double asterisk can be used to create an empty
dictionary in a similar way (pg 149)
MODULES
Modules are separate files that functions can be imported from into the main program.
The import statement tells python to make code in the module available in the currently
running file.
To call a function from an imported module, enter the name of the module you imported
followed by the name of the function separated by a dot.
(module_name.fucntion_name())
1. import pizza
2.
3. pizza.make_pizza(16, pepperoni)
GIVING AN ALIAS TO FUNCTIONS: if function name is long the function name can be
given an alias:
From module_name import function_name as fn, where function I now called upon as fn.
()
NOTE: you can also give a module an alias as import module_name as mn (eg matplotlib
as plt)
Scripts: a python file intended to be run directly (i.e not just classes and dunctions)
MATH MODULE
Import math: included math methods and functions:
Sqrt()
.ceil() rounds up
NUMPY ARRAY
Import numpy as np: used to work with arrays. An array object in numPy is called ndarray
c=which can be created by using array() function
1. import numpy as np
2. narr = np.array([[0,1,2,3,4,5],
3. [6,7,8,9,10,11],
4. [12,13,14,15,16,17],
5. [18,19,20,21,22,23],
6. [24,25,26,27,28,29],
7. [30,31,32,33,34,35]])
8.
9. #in purple 25-27
10. print(narr[4,1:4])
11.
CLASSES
The __init__() method:
A function that is apart of a class is a method. This method runs automatically whenever
we create aa new instance based on the class. It always starts with the “self” parameter
in its method definition. It must start with this parameter as when python calls this
method later to create an instance of the class, the method call will automatically pass
the self argument. It gives the individual instance access to the methods within the class.
When making an instance of the class python calls the __init__ () method, you pass any
arguments, self is passed autoatially The two variabels defined from the parameters
have the prefix self. Any variable with the prefix self is available to every method in th
class . The line self.name = name would take the value associated with the parameter
name which is the attached to the instance being created through “self” (theres
variabels that are accessible to instances like this are called variables). Other methods in
the class also have the parameter self meaning instances created will have access to
these methods.
1. class Dog:
2.
3. Def __init__(self, name, age):
4. Self.name = name
5. Self.age = age
6.
7. Def sit(self):
8. Print(f”{self.name} is now sitting”)
9.
10. Def roll_over(self):
11. Print(f”{self.name} rolled over!”
1. Class Dog:
2. My_dog = Dog(“Willie”, 6)
Python calls the __init__ method with the associated arguments. The method creates an
instance representing this particular dog and sets name and age attrbutes using values
provided in the class call. Python returns an instance representing the dog which is
assigned to the variable my_dog.
Accessing attributes:
Calling Methods: after creating the instance from the class, dot notation can be used to
call any method defined in the class. When python reads the call it looks for the method
in the class and runs that.
1. Class Dog:
2. …
3. My_dog = Dog(“Willie”, 6)
4. My_dog.sit()
5. My_dog.roll_over()
1. My_dog = Dog(“Willie”, 6)
2. your_dog = Dog(“lucy”, 3)
3. my_dog.sit()
4. your_dog.sit()
1. Directly through an instance: pass new value to a method that handles the
updating internally
1. Class Car:
2. Def __init__(self, make, model, year):
3. Self.make = “make”
4. Self.model = “model”
5. Self.year = "year”
6. Self.odometer_reading = 0
7.
8. Def read_odometer(self):
9. Print(f”this car has {selfodometer_reading} miles on it”)
10. my_new_car = Car(‘audi’, ‘a4’, 2019)
11. my_new_car.odometer_reading = 23
12. My_new_car.read_odometer()
13.
1. def_increment_odometer(self, miles):
2. self.odometer_reading += miles
3. my_used_car.increment_odometer(100)
4. my_used_car.read_odometer()
Inheritance:
When writing a new class based on an existsing class, you’ll often want to call the __init__
() method from the parent class, which initialises any attributes that were defined in the
parent __init__() method and make them available in the child class. Use the super()
function to call a metho from the parent class.
1. class ElectricCar(Car):
2. def __init__(self, make, model, year):
3. super().__init__(make,model,year)
4.
5. my_tesla = ElectricCar(‘tesla’, ‘model s’, 2019
You can add attributes and methods necessary to differentiate the child class from the
parent class.
11.class ElectricCar(Car):
2. def __init__(self, make, model, year):
3. super().__init__(make,model,year)
4. self.battery_size = 75
5. def desrcirbe_battery(self):
6. Print(f”This car has a {self.battery_size}-kWh battery.”)
7. my_tesla = ElectricCar(‘tesla’, ‘model s’, 2019)
8. my_tesla.descrine_battery()
Define a method oin the child class with the same name as the method you want to
override in the parent class, python will disregard the parent class method and only pay
attention to the method defined in the child class.
Instances as attributes: when classes start getting long with too many attributes and
methods can split it:
1. class Battery:
2. ef __init__(self, battery_size = 75):
3. Self.battery_size = battery_size
4.
5. Def describe_battery(self):
6. print(f”this car has a {self.battery_size}-kWh battery.”)
7. class ElectricCar(Car):
…..
8. self.battery = Battery()
9.
10. my_tesla.battery.describe_battery()
Importing classes:
From module import class1, class 2 as alias etc. (can also just import entire module)
Randint() from ramdom module takes two integer arguments and returns a randomly
selected integer between and including those numbers
FILES:
Reading from files:
To work with an external file you must open it with the open() function that has one
argument (name of file). Python then assigns the open file to variable thatcan be worked
with later in the program. The keyword with closes the file when access is no longer
needed. (could also be done by doing open() and close())
Note: read() returns an empty string when it reaches the end of the file (blank line) which
can be removed by using rstrip() in the call to print (contents.rstrip()) and returns x
number of charcaters when given a parameter.
Reading line by line: to examine each line from a file one at a time you can use a for loop
with rstrip() to prevent blank lines:
1. Filename = “pi_digits.txt”
2. with open(filename) as file_object:
3. for line in file_object:
4. print(line.rstrip())
Making a list of lines from a file: when using the keyword with, the file object returned by
open() is only available inside the with block that contains it, to retain access to a files
ocntents outside the with block you can store the files lines in a list inside the block ad
then work with that list where method readines() can be used. Split() method can also be
used to build a list of words from a string b splitting at every white space.
To write to a file, call open() with a second argument telling python to write the file, note:
write mode erases any existing content
1. filename = ‘programming.txt’
2. with open(filename, ‘w’) as file_ object:
3. file_object.write(‘I love programming’)
Different modes:
Open() automatically creates the file you’re writing to if it doesn’t already exist
Appending to a file: to add content to a file instead of writing over existing content (if file
doesn’t exist, python will create empty file for you)
1. filename = ‘programming.txt’
2. with open(filename, ‘a’) as file_ object:
3. file_object.write(‘I love programming’)
REGEX
RegEx can be used to check if a string contains the specified search pattern. Start by
importing re:
Sub(find, replace ) repleaces the matches of the texts of your choice and it returns th
string
Split() method splits a string into a list of its constituent words (separated by
whitsoeace)
Exceptions:
Exceptions handle errors that arise during a programs execution, allowing the program to
keep running rather than crash when encountering an error. Execptions are handled with
try-except blocks. Can also leave except block empty with just pass to fail silently.
1. try:
2. print(5/0)
3. except ZeroDivisionError:
4. print(“You can’t divide by zero!”)
5. else:
6. print(answer)
FileNotFoundError: handles missing files
1. file_name = ‘alice.txt’
2.
3. try:
4. with open(filename) as f:
5. contents = f.read()
6. except FileNotFoundError:
7. print(f”Sorry {filename} does not exist”)
Using “as”
1. try:
2. x="ENGG"
3. y=1810
4. print(x+y)
5. except TypeError as e_msg:
6. print(e_msg)
7.
Finally block is executed regardless of whether the try block raises an error or not:
1. try:
2. # Code that might throw exceptions...
3. ...
4. except exception_name:
5. # This will catch the error if the exception raised is an
instance of exception_name.
6. # Put here what you want to happen if this type of exception
occurs.
7. ...
8. except another_exception_name:
9. # We can have multiple excepts for different types of
exceptions!
10. ...
11. finally:
12. # Optional: this always executes regardless of whether an
exception was
13. # thrown or not.
14. ...
15.
Raising Exceptions:
raise <exception_name(description)>
Testing:
The module unitest from the pythton standard library provides tools for testing your
code. Unit test verifies that one specific aspect of a function’s behaviour is correct. Test
case is a collection of unit tests that together prive a function behaves as its supposed
to.
Import unittest module and create a class that inherits from unittest.TestCase and write
a series of methods to test different aspects function:
1. import unittest
2. from name_function import get_formatted_name:
3. class NamesTestCase(unittest.TestCase):
4.
5. def test_first_last_name(self):
6. formatted_name = get_formatted_name(‘janis’, ‘joplin’)
7. self.assertEqual(formatted_name, ‘Janis Joplin’)
8.
9. if __name__ == “__main__”:
10. unittest.main()
Class must inherit from unit.TestCase so python knows how to run tests written. Any
method starting with test_ will automatically be run when the class is run. assertEqual()
confirms result you recevievd from function call (first argument) matches the one you
expect (second argument)
__name__ == “__main__” refers to whether the file being run is the main program.
1. import unittest
2. from leapyear_ex import leap_year
3.
4. class TestLeapyear(unittest.TestCase):
5. def test_non_integer(self):
6. self.assertRaisesRegex(Exception, "You must pass an integer", leap_year,
"2000")
7.
8.
9. if __name__ == '__main__':
10. unittest.main()
Python time module provides .process_time() that returns the value in fractional seconds
of the sum of the system and use CPU time of the current process.
from time import process_time #import the module time and use process_time
Importlib: provides the implementation of the import statement in python source code
Glob: find all the pathnames matching a specified pattern according to the rules used by
Unix Shell
1. import os
2. import importlib
3. from glob import glob
4. from time import process_time
5.
6. for pth in glob('odd_*'):
7. filename = os.path.splitext(pth)[0]
8. mod = importlib.import_module(filename)
9.
10. start = process_time() #time will be saved
11. mod.odd_num(100) #after we test it
12. end = process_time() #time will be saved
13. print('{} Runtime: {}'.format(filename,end-start))
Go through lab 11
VARIABLES:
Variables that are created outside a function are known as global variables which can be
used by everyone both inside and outside fucnitons.
Variables declared inside functions (local variables) can only be used within the function.
To make a variable inside a function glocal use global keyword
1. def printA():
2. global a
3. a = "test"
4. print("The value of a is {}".format(a))
5.
6. printA()
7.
8. print(a)
Matplotlib
Fig – represents the entire figure or collection of plots tha are generates
Linewidth parameter = controls thickness of the line that the plot generates
fontdict
Scatter plots:
1. X_values=[1, 2, 3, 4, 5]
2. Y_values=[1, 4, 9, 16, 25]
3. Fig, ax =plt.subplots()
4. Ax.scatter(x_values, y_values, s=100)
5. Ax.axis(0,5,0,25)
6.
Bar grpahs: bar(x,y, color=””, width=, ) for vertical bargraph and barh(x,y,color=’’,
height=) for horizontal
Bar_label()
To create a group bar chart use a dictionary inside a dictionary and use subplots()
1. xLocs = []
2. #define the location of each bar for a student
3. #len(assess_item) is 2 so - for x in range(2) will be 0, 1
4. for x in range(len(assess_item)):
5. xLocs.append(x+width*i)
6. i = i + 1
7. print(xLocs)
8.
Line graph
Np.arrange(start, end) returns eqaully spaced values from the interval [start, end)
PANDAS
Import pandas as pd.
A pandas series is like a column in a table – one dimensional arra holding data of any
type pd.series(x, index=). When nothing is specified the vakeus are labelled with their
index number. To create own index provide separate list.
1. import pandas as pd
2.
3. students = ['Paul', 'Hamish', 'Eileen', 'Brian']
4. st_series = pd.Series(students, index = ["1st", "2nd", "3rd", "4th"])
5.
6. print(st_series)
7.
Output:
1. 1st Paul
2. 2nd Hamish
3. 3rd Eileen
4. 4th Brian
5. dtype: object
6.
Can also turn dicionaries into pandas and set index as keys.
1. import pandas as pd
2.
3. weather = {"day1": 'Sunny', "day2": 'Rainy', "day3": 'Cloudy'}
4. weather_series = pd.Series(weather, index = ["day1", "day3"])
5.
6. print(weather_series)
1. day1 Sunny
2. day3 Cloudy
3. dtype: object
Dataframes:
A dataframe is a two dimension structure (like a table with rows and column often done
with multi-dimensional dictionaries.
1. import pandas as pd
2.
3. grade={
4. "BTS_V":{
5. "age": 25,
6. "marks": 85
7. },
8. "Emma":{
9. "age": 31,
10. "marks": 91
11. },
12. "Spongebob":{
13. "age": 25,
14. "marks": 50
15. }
16. }
17.
18. #load data into a DataFrame object/instance:
19. df_grade = pd.DataFrame(grade)
20.
21. print(df_grade)
Keyword loc: can be used to return one or more specified rows form the dataframe:
loc[[x],[y]] where x is fro the row label/index and y is fro columns;
import pandas as pd
1. grade={
2. "BTS_V":{
3. "age": 25,
4. "marks": 85
5. },
6. "Emma":{
7. "age": 31,
8. "marks": 91
9. },
10. "Spongebob":{
11. "age": 25,
12. "marks": 50
13. }
14. }
15.
16. #load data into a DataFrame object/instance:
17. df_grade = pd.DataFrame(grade)
18.
19. print(df_grade.loc[["age","marks"],["BTS_V","Emma"]])
20.
1. BTS_V Emma
2. age 25 31
3. marks 85 91
Pandas and reading from csv files: read_csv() function stores everything in a table
1. import pandas as pd
2. import matplotlib.pyplot as plt
3.
4. df_cal = pd.read_csv('calories.csv')
5. df_cal.plot()
6.
7. plt.savefig('cal_line.png')
INTERPOLATION
Linear interpolation and Cubic Spline interpolation:
LINEAR INTERPOLATION
Estimates missing values by connecting dots in a straight line between known points
Fig, ax(x,y,’ro’)
F = interplotae.interpld(x,y)
Xestimated = np.arrange(1,19,0.5)
Yestimated=f(xestimate
Fig, ax =plt.subplots()
Fig, ax(x,
1. df_shome = pd.read_csv('smart_home.csv')
2. fig, ax = plt.subplots()
3. ax.plot(df_shome['hour'], df_shome['dust'],"ro")
4.
5.
6. f = interpolate.interpld(df_shome['hour'], df_shome['dust'])
7. #x_est for checking every 30 mins (0.5 of an hour) in the x-axis
8. x_est = np.arange(1,19, 0.5)
9. #y_est that presents the estimated value of every 30 mins (aligned with the x_est)
based on the trained function f
10. y_est = f(x_est)
11. ax.plot(x_est, y_est,"b+")
12.
Interpld() method creates a function based on fixed sata points which can be evaluated
anywhere within the domain defined by the given data using linea rinterpolation
To extrapolate:
Cubsic spline is same as linear except method is called: CubicSpline() and doesn’t need
fill_vallue to extrapolate.
Things to revise:
Fig, ax
Boolean operators
Google colab ?
Fig, ax = plt.subplots()
Fig, ax(x,y,’ro’)
F = interpolate.interpld(x,y,fill_vale=@extrapolate@)
F= interpolate.cubicSpline(x,y)
X_est = np.arrange(1,20,0.5)