You’ll be able to:
list, dict)filter and pandas masksYou’ll be able to:
You’ll be able to:
picklepathlib library to simplify file operationsYou’ll be able to:
You’ll be able to:
You’ll be able to:
map and filter
mapLet’s suppose we have a list of prices:
These prices will suffer an update of 4.5%. How can we update them?
With what we’ve learned so far, we could write a loop.
Or use lambda…
⚠️ Keep your lambdas short. ⚠️
If you have complex logic, transfer it to a “normal” function where the logic will be clearer.
Why are we converting the result of map to a list?
map actually returns an iterable, not a list (like zip and enumerate)
And it can also receive any iterable (tuple, dict, …), not just a list.
Another example:
Are you really going to use this?
Often people don’t directly use Python’s default map, but map is often implemented in other data structures, such as…
filterfilter works just like map
but instead of applying a function to every value, we’re picking which values we want to keep.
Because we’re choosing which values to keep, the function that we give to filter must return a bool (True or False).
Wil you use this?
Probably not! In Pandas, we actually filter in different ways, like:
Why does that work?
When we compare the column “category” with the value “vegetables”, we get another column of the same size indicating where that comparison was True or False.
This column is the mask that will select the rows of the original dataframe where the comparison is True.
Modules and packages
import our own codeIn Python, we can create our own modules to store code and import that code into other programs.
Why do this? Reusability and modularity.
You can download the notebook here and read it directly in Github.
Files
picklejson.dump, json.load, json.dumps, json.loadsThis gives an error, because this file does not exist.
In [66]: f = open("test_file.txt") # open a file
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-66-a7d550966829> in <module>
----> 1 f = open("test_file.txt") # open a file
FileNotFoundError: [Errno 2] No such file or directory: 'test_file.txt'There are 3 ways of opening a file:
If a mode is not speficied when opening a file, the default is “r”. That is why we got an error.
Let’s create our file first.
Now, let’s read it.
We can add a + modifier to any mode, and it allows the modes to both read and write.
"r+" still doesn’t create a file if it doesn’t exist though.
It’s easier to forget closing files, specially when there are many operations between opening and closing.
The recommended way of opening and closing files is to use a context manager
When we use with, the file is automatically closed when the block of instructions inside with is finished.
Binary files store data in a format that is not human readable.
They’re very useful to store numeric data because we can fit more numbers within the same memory space.
To use files in binary mode, we simply add a “b” to the modes we’ve already seen so far.
They will also be useful to store trained models to be deployed or used by other people.
In Python, we can store almost any object in a binary format with the pickle module.
Let’s create a dict to store in a binary file.
Storing an object in a pickle file
JSON (JavaScript Object Notation) is a human-readable text format for storing structured data.
It maps naturally to Python dicts and lists.
We can also convert to and from JSON strings without touching a file.
| JSON | pickle | |
|---|---|---|
| Human-readable | ✅ | ❌ |
| Cross-language | ✅ | ❌ |
| Any Python object | ❌ | ✅ |
Use JSON for configs, APIs, and data exchange (not storage!).
Use pickle for Python-specific objects (e.g. trained models).
I recommend the use of the pathlib library anytime you need to deal with files.
It makes working with files much easier, since there are things that change when our code executes in Windows, MacOS, Linux, etc.
By using pathlib, many of these differences are abstracted away.
We also have many utilities that make life easier.
create a Path
Path is the main object to use, and it provides many methods to streamline file operations.
open, write, read
Output:
.readlines() is a new method, that reads the whole file and splits the content by lines in a list.
read and write “shortcuts”
Output of line 1:
Output of line 6:
They also work with paths that are directories and it becomes easier to list all files inside.
List all files and folders inside code/
List all .py files inside code/, recursively.
Path objects have many more useful methods, but we won’t explore them in this course:
Exceptions
ValueError exception is thrown.imaginary_file.txt does not exist, so a FileNotFoundError exception is thrown.When we get an exception, we get:
FileNotFoundErrorNo such file or directory: 'imaginary_file.txt' There may be a long list of function calls.
Traceback (most recent call last):
File "script.py", line 8, in <module>
avs = averages(data_fn)
File "mypackage/stats.py", line 17, in averages
data = read_csv(filename)
File "mypackage/file_utils.py", line 7, in read_csv
with open(fn) as f:
FileNotFoundError: [Errno 2] No such file or directory: 'imaginary_file.txt'It’s a traceback because it allows us to trace the problem back to its root.
try block to catch an exception and stop the program from failing.We can catch just some kinds of exceptions too.
We can also catch more exceptions or combine them.
Classes
Object Oriented Programming (OOP)
class Vehicle:
def __init__(self, color): # special method, the constructor
self.color = color # this is an attribute
self.acc = 0 # another attribute
def accelerate(self): # this is a method
self.acc += 2 # fetching a predefined
# attribute and modifying it
def deaccelerate(self): # another method
self.acc -= 2instatiating classes
To use a class, we call it like we call functions.
classes from other packages
Remember the Pandas DataFrame?
It’s a class!
read_excel function reads the contents of the Excel file into a newly created DataFrame object.map is a method.[ ], is the implementation of the special method __getitem__[ ] is also the implementation of __setitem__.inheritance
LinearRegression class inherits from MultiOutputMixin, RegressorMixin and LinearModel.DecisionTreeClassifier inherits from ClassifierMixin and BaseDecisionTree.torch.nn.Module.What you need to know about OOP?
RegressorMixin.Debugging
import pdb; pdb.set_trace() or breakpoint()python -m pdb some_program.pypdb cheatsheet
map
apply a function to a “list” of values
pandas and map
modules and packages
.py) files in the same folder as our program can be directly imported.__init__.py files)files
context manager
The file is closed for us at the end of the context (with block)
binary
We can store (almost) any Python object in a binary file with pickle
Human-readable, cross-language format. Maps to dicts and lists.
When something unexpected happens, Python throws an exception.
If not handled, exceptions stop program execution.
Read from bottom to top: - What exception? FileNotFoundError - Where did it happen? utils.py, line 5, inside load_file - How did we get there? Called from line 15, called from line 8
⚠️ Catch specific exceptions when possible!
class Model:
def __init__(self, name, learning_rate): # constructor
self.name = name # attribute
self.learning_rate = learning_rate
self.trained = False # attribute
def train(self, data): # method
# training logic here
self.trained = True
def predict(self, features): # method
if not self.trained:
raise ValueError("Model not trained yet")
# prediction logic hereEverything in Python is an object from some class!
class BaseModel:
def __init__(self, name):
self.name = name
self.trained = False
def train(self, data):
self.trained = True
class NeuralNetwork(BaseModel): # inherits from BaseModel
def train(self, data): # override parent method
print("Training neural network...")
super().train(data) # call parent's train methodMany ML libraries use inheritance:
Or run script in debug mode:
Use pdb to inspect variables and understand program flow!