Python Cheatsheet
Python Cheatsheet
# Contents
ToC = {
'1. Collections': [List, Dictionary, Set, Tuple, Range, Enumerate, Iterator, Generator],
'2. Types': [Type, String, Regular_Exp, Format, Numbers, Combinatorics, Datetime],
'3. Syntax': [Args, Inline, Closure, Decorator, Class, Duck_Type, Enum, Exception],
'4. System': [Exit, Print, Input, Command_Line_Arguments, Open, Path, OS_Commands],
'5. Data': [JSON, Pickle, CSV, SQLite, Bytes, Struct, Array, Memory_View, Deque],
'6. Advanced': [Threading, Operator, Introspection, Metaprograming, Eval, Coroutine],
'7. Libraries': [Progress_Bar, Plot, Table, Curses, Logging, Scraping, Web, Profile,
NumPy, Image, Audio, Games, Data, Cython]
}
# Main
# List
<list>.sort()
<list>.reverse()
<list> = sorted(<collection>)
<iter> = reversed(<list>)
sum_of_elements = sum(<collection>)
elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)]
sorted_by_second = sorted(<collection>, key=lambda el: el[1])
sorted_by_both = sorted(<collection>, key=lambda el: (el[1], el[0]))
flatter_list = list(itertools.chain.from_iterable(<list>))
product_of_elems = functools.reduce(lambda out, el: out * el, <collection>)
list_of_chars = list(<str>)
Module operator provides functions itemgetter() and mul() that offer the same
functionality as lambda expressions above.
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 1/51
7/5/2020 Comprehensive Python Cheatsheet
<int> = <list>.count(<el>) # Returns number of occurrences. Also works on strings.
index = <list>.index(<el>) # Returns index of first occurrence or raises ValueError.
<list>.insert(index, <el>) # Inserts item at index and moves the rest to the right.
<el> = <list>.pop([index]) # Removes and returns item at index or from the end.
<list>.remove(<el>) # Removes first occurrence of item or raises ValueError.
<list>.clear() # Removes all items. Also works on dictionary and set.
# Dictionary
Counter
# Set
<set> = set()
Frozen Set
<frozenset> = frozenset(<collection>)
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 2/51
7/5/2020 Comprehensive Python Cheatsheet
# Tuple
Tuple is an immutable and hashable list.
<tuple> = ()
<tuple> = (<el>, )
<tuple> = (<el_1>, <el_2> [, ...])
Named Tuple
# Range
<range> = range(to_exclusive)
<range> = range(from_inclusive, to_exclusive)
<range> = range(from_inclusive, to_exclusive, ±step_size)
from_inclusive = <range>.start
to_exclusive = <range>.stop
# Enumerate
# Iterator
Itertools
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 3/51
7/5/2020 Comprehensive Python Cheatsheet
# Generator
Any function that contains a yield statement returns a generator.
Generators and iterators are interchangeable.
# Type
Everything is an object.
Every object has a type.
Type and class are synonymous.
Each abstract base class speci es a set of virtual subclasses. These classes are then recognized
by isinstance() and issubclass() as subclasses of the ABC, although they are really not.
┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┓
┃ │ Sequence │ Collection │ Iterable ┃
┠──────────────────┼────────────┼────────────┼────────────┨
┃ list, range, str │ ✓ │ ✓ │ ✓ ┃
┃ dict, set │ │ ✓ │ ✓ ┃
┃ iter │ │ │ ✓ ┃
┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛
┏━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┓
┃ │ Integral │ Rational │ Real │ Complex │ Number ┃
┠────────────────────┼──────────┼──────────┼──────────┼──────────┼──────────┨
┃ int │ ✓ │ ✓ │ ✓ │ ✓ │ ✓ ┃
┃ fractions.Fraction │ │ ✓ │ ✓ │ ✓ │ ✓ ┃
┃ float │ │ │ ✓ │ ✓ │ ✓ ┃
┃ complex │ │ │ │ ✓ │ ✓ ┃
┃ decimal.Decimal │ │ │ │ │ ✓ ┃
┗━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 4/51
7/5/2020 Comprehensive Python Cheatsheet
# String
<str> = <str>.replace(old, new [, count]) # Replaces 'old' with 'new' at most 'count' times.
<str> = <str>.translate(<table>) # Use `str.maketrans(<dict>)` to generate table.
Property Methods
┏━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┓
┃ │ [ !#$%…] │ [a-zA-Z] │ [¼½¾] │ [²³¹] │ [0-9] ┃
┠───────────────┼──────────┼──────────┼──────────┼──────────┼──────────┨
┃ isprintable() │ ✓ │ ✓ │ ✓ │ ✓ │ ✓ ┃
┃ isalnum() │ │ ✓ │ ✓ │ ✓ │ ✓ ┃
┃ isnumeric() │ │ │ ✓ │ ✓ │ ✓ ┃
┃ isdigit() │ │ │ │ ✓ │ ✓ ┃
┃ isdecimal() │ │ │ │ │ ✓ ┃
┗━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛
# Regex
import re
<str> = re.sub(<regex>, new, text, count=0) # Substitutes all occurrences with 'new'.
<list> = re.findall(<regex>, text) # Returns all occurrences as strings.
<list> = re.split(<regex>, text, maxsplit=0) # Use brackets in regex to include the matches.
<Match> = re.search(<regex>, text) # Searches for first occurrence of the pattern.
<Match> = re.match(<regex>, text) # Searches only at the beginning of the text.
<iter> = re.finditer(<regex>, text) # Returns all occurrences as match objects.
Match Object
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 5/51
7/5/2020 Comprehensive Python Cheatsheet
Special Sequences
By default digits, alphanumerics and whitespaces from all alphabets are matched, unless
'flags=re.ASCII' argument is used.
Use a capital letter for negation.
# Format
Attributes
General Options
Strings
Numbers
Floats
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 6/51
7/5/2020 Comprehensive Python Cheatsheet
Comparison of presentation types:
┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┓
┃ │ {<float>} │ {<float>:f} │ {<float>:e} │ {<float>:%} ┃
┠───────────────┼─────────────────┼─────────────────┼─────────────────┼─────────────────┨
┃ 0.000056789 │ '5.6789e-05' │ '0.000057' │ '5.678900e-05' │ '0.005679%' ┃
┃ 0.00056789 │ '0.00056789' │ '0.000568' │ '5.678900e-04' │ '0.056789%' ┃
┃ 0.0056789 │ '0.0056789' │ '0.005679' │ '5.678900e-03' │ '0.567890%' ┃
┃ 0.056789 │ '0.056789' │ '0.056789' │ '5.678900e-02' │ '5.678900%' ┃
┃ 0.56789 │ '0.56789' │ '0.567890' │ '5.678900e-01' │ '56.789000%' ┃
┃ 5.6789 │ '5.6789' │ '5.678900' │ '5.678900e+00' │ '567.890000%' ┃
┃ 56.789 │ '56.789' │ '56.789000' │ '5.678900e+01' │ '5678.900000%' ┃
┃ 567.89 │ '567.89' │ '567.890000' │ '5.678900e+02' │ '56789.000000%' ┃
┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┛
┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┓
┃ │ {<float>:.2} │ {<float>:.2f} │ {<float>:.2e} │ {<float>:.2%} ┃
┠───────────────┼─────────────────┼─────────────────┼─────────────────┼─────────────────┨
┃ 0.000056789 │ '5.7e-05' │ '0.00' │ '5.68e-05' │ '0.01%' ┃
┃ 0.00056789 │ '0.00057' │ '0.00' │ '5.68e-04' │ '0.06%' ┃
┃ 0.0056789 │ '0.0057' │ '0.01' │ '5.68e-03' │ '0.57%' ┃
┃ 0.056789 │ '0.057' │ '0.06' │ '5.68e-02' │ '5.68%' ┃
┃ 0.56789 │ '0.57' │ '0.57' │ '5.68e-01' │ '56.79%' ┃
┃ 5.6789 │ '5.7' │ '5.68' │ '5.68e+00' │ '567.89%' ┃
┃ 56.789 │ '5.7e+01' │ '56.79' │ '5.68e+01' │ '5678.90%' ┃
┃ 567.89 │ '5.7e+02' │ '567.89' │ '5.68e+02' │ '56789.00%' ┃
┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┛
Ints
{90:c} # 'Z'
{90:b} # '1011010'
{90:X} # '5A'
# Numbers
Types
Basic Functions
Math
Statistics
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 7/51
7/5/2020 Comprehensive Python Cheatsheet
Random
Bin, Hex
Bitwise Operators
# Combinatorics
Every function returns an iterator.
If you want to print the iterator, you need to pass it to the list() function rst!
>>> combinations('abc', 2)
[('a', 'b'), ('a', 'c'),
('b', 'c')]
>>> combinations_with_replacement('abc', 2)
[('a', 'a'), ('a', 'b'), ('a', 'c'),
('b', 'b'), ('b', 'c'),
('c', 'c')]
>>> permutations('abc', 2)
[('a', 'b'), ('a', 'c'),
('b', 'a'), ('b', 'c'),
('c', 'a'), ('c', 'b')]
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 8/51
7/5/2020 Comprehensive Python Cheatsheet
# Datetime
Module 'datetime' provides 'date' <D>, 'time' <T>, 'datetime' <DT> and 'timedelta' <TD>
classes. All are immutable and hashable.
Time and datetime objects can be 'aware' <a>, meaning they have de ned timezone, or
'naive' <n>, meaning they don't.
If object is naive, it is presumed to be in the system's timezone.
Constructors
Now
Timezone
Encode
Decode
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 9/51
7/5/2020 Comprehensive Python Cheatsheet
Format
Arithmetics
<D/DT> = <D/DT> ± <TD> # Returned datetime can fall into missing hour.
<TD> = <D/DTn> - <D/DTn> # Returns the difference, ignoring time jumps.
<TD> = <DTa> - <DTa> # Ignores time jumps if they share tzinfo object.
<TD> = <DT_UTC> - <DT_UTC> # Convert DTs to UTC to get the actual delta.
# Arguments
Inside Function Call
<function>(<positional_args>) # f(0, 0)
<function>(<keyword_args>) # f(x=0, y=0)
<function>(<positional_args>, <keyword_args>) # f(0, y=0)
# Splat Operator
Inside Function Call
Splat expands a collection into positional arguments, while splatty-splat expands a dictionary
into keyword arguments.
args = (1, 2)
kwargs = {'x': 3, 'y': 4, 'z': 5}
func(*args, **kwargs)
Splat combines zero or more positional arguments into a tuple, while splatty-splat combines
zero or more keyword arguments into a dictionary.
def add(*a):
return sum(a)
>>> add(1, 2, 3)
6
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 10/51
7/5/2020 Comprehensive Python Cheatsheet
Legal argument combinations:
def f(x, y, z): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)
def f(*, x, y, z): # f(x=1, y=2, z=3)
def f(x, *, y, z): # f(x=1, y=2, z=3) | f(1, y=2, z=3)
def f(x, y, *, z): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)
def f(*args, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)
def f(x, *args, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)
def f(*args, y, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3)
def f(x, *args, z, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)
Other Uses
# Inline
Lambda
Comprehensions
out = []
for i in range(10):
for j in range(10):
out.append(i+j)
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 11/51
7/5/2020 Comprehensive Python Cheatsheet
Any, All
If - Else
# Closure
We have a closure in Python when:
def get_multiplier(a):
def out(b):
return a * b
return out
If multiple nested functions within enclosing function reference the same value, that
value gets shared.
To dynamically access function's rst free variable use
'<function>.__closure__[0].cell_contents'.
Partial
Partial is also useful in cases when function needs to be passed as an argument, because
it enables us to set its arguments beforehand.
A few examples being: 'defaultdict(<function>)', 'iter(<function>,
to_exclusive)' and dataclass's 'field(default_factory=<function>)'.
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 12/51
7/5/2020 Comprehensive Python Cheatsheet
Non-Local
If variable is being assigned to anywhere in the scope, it is regarded as a local variable, unless
it is declared as a 'global' or a 'nonlocal'.
def get_counter():
i = 0
def out():
nonlocal i
i += 1
return i
return out
# Decorator
A decorator takes a function, adds some functionality and returns it.
@decorator_name
def function_that_gets_passed_to_decorator():
...
Debugger Example
def debug(func):
@wraps(func)
def out(*args, **kwargs):
print(func.__name__)
return func(*args, **kwargs)
return out
@debug
def add(x, y):
return x + y
Wraps is a helper decorator that copies the metadata of the passed function (func) to the
function it is wrapping (out).
Without it 'add.__name__' would return 'out'.
LRU Cache
Decorator that caches function's return values. All function's arguments must be hashable.
@lru_cache(maxsize=None)
def fib(n):
return n if n < 2 else fib(n-2) + fib(n-1)
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 13/51
7/5/2020 Comprehensive Python Cheatsheet
Parametrized Decorator
A decorator that accepts arguments and returns a normal decorator that accepts a function.
def debug(print_result=False):
def decorator(func):
@wraps(func)
def out(*args, **kwargs):
result = func(*args, **kwargs)
print(func.__name__, result if print_result else '')
return result
return out
return decorator
@debug(print_result=True)
def add(x, y):
return x + y
# Class
class <name>:
def __init__(self, a):
self.a = a
def __repr__(self):
class_name = self.__class__.__name__
return f'{class_name}({self.a!r})'
def __str__(self):
return str(self.a)
@classmethod
def get_class_name(cls):
return cls.__name__
print(<el>)
print(f'{<el>}')
raise Exception(<el>)
loguru.logger.debug(<el>)
csv.writer(<file>).writerow([<el>])
print([<el>])
print(f'{<el>!r}')
>>> <el>
loguru.logger.exception()
Z = dataclasses.make_dataclass('Z', ['a']); print(Z(<el>))
Constructor Overloading
class <name>:
def __init__(self, a=None):
self.a = a
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 14/51
7/5/2020 Comprehensive Python Cheatsheet
Inheritance
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Employee(Person):
def __init__(self, name, age, staff_num):
super().__init__(name, age)
self.staff_num = staff_num
Multiple Inheritance
class A: pass
class B: pass
class C(A, B): pass
MRO determines the order in which parent classes are traversed when searching for a
method:
>>> C.mro()
[<class 'C'>, <class 'A'>, <class 'B'>, <class 'object'>]
Property
class MyClass:
@property
def a(self):
return self._a
@a.setter
def a(self, value):
self._a = value
>>> el = MyClass()
>>> el.a = 123
>>> el.a
123
Dataclass
Decorator that automatically generates init(), repr() and eq() special methods.
@dataclass(order=False, frozen=False)
class <class_name>:
<attr_name_1>: <type>
<attr_name_2>: <type> = <default_value>
<attr_name_3>: list/dict/set = field(default_factory=list/dict/set)
Objects can be made sortable with 'order=True' and/or immutable and hashable with
'frozen=True'.
Function eld() is needed because '<attr_name>: list = []' would make a list that is
shared among all instances.
Default_factory can be any callable.
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 15/51
7/5/2020 Comprehensive Python Cheatsheet
Inline:
Slots
Mechanism that restricts objects to attributes listed in 'slots' and signi cantly reduces their
memory footprint.
class MyClassWithSlots:
__slots__ = ['a']
def __init__(self):
self.a = 1
Copy
# Duck Types
A duck type is an implicit type that prescribes a set of special methods. Any object that has
those methods de ned is considered a member of that duck type.
Comparable
class MyComparable:
def __init__(self, a):
self.a = a
def __eq__(self, other):
if isinstance(other, type(self)):
return self.a == other.a
return NotImplemented
Hashable
Hashable object needs both hash() and eq() methods and its hash value should never
change.
Hashable objects that compare equal must have the same hash value, meaning default
hash() that returns 'id(self)' will not do.
That is why Python automatically makes classes unhashable if you only implement eq().
class MyHashable:
def __init__(self, a):
self._a = a
@property
def a(self):
return self._a
def __eq__(self, other):
if isinstance(other, type(self)):
return self.a == other.a
return NotImplemented
def __hash__(self):
return hash(self.a)
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 16/51
7/5/2020 Comprehensive Python Cheatsheet
Sortable
With total_ordering decorator, you only need to provide eq() and one of lt(), gt(), le() or
ge() special methods.
@total_ordering
class MySortable:
def __init__(self, a):
self.a = a
def __eq__(self, other):
if isinstance(other, type(self)):
return self.a == other.a
return NotImplemented
def __lt__(self, other):
if isinstance(other, type(self)):
return self.a < other.a
return NotImplemented
Iterator
class Counter:
def __init__(self):
self.i = 0
def __next__(self):
self.i += 1
return self.i
def __iter__(self):
return self
Callable
All functions and classes have a call() method, hence are callable.
When this cheatsheet uses '<function>' as an argument, it actually means
'<callable>'.
class Counter:
def __init__(self):
self.i = 0
def __call__(self):
self.i += 1
return self.i
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 17/51
7/5/2020 Comprehensive Python Cheatsheet
Context Manager
class MyOpen:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.file = open(self.filename)
return self.file
def __exit__(self, exc_type, exception, traceback):
self.file.close()
class MyIterable:
def __init__(self, a):
self.a = a
def __iter__(self):
return iter(self.a)
def __contains__(self, el):
return el in self.a
Collection
class MyCollection:
def __init__(self, a):
self.a = a
def __iter__(self):
return iter(self.a)
def __contains__(self, el):
return el in self.a
def __len__(self):
return len(self.a)
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 18/51
7/5/2020 Comprehensive Python Cheatsheet
Sequence
class MySequence:
def __init__(self, a):
self.a = a
def __iter__(self):
return iter(self.a)
def __contains__(self, el):
return el in self.a
def __len__(self):
return len(self.a)
def __getitem__(self, i):
return self.a[i]
def __reversed__(self):
return reversed(self.a)
ABC Sequence
class MyAbcSequence(abc.Sequence):
def __init__(self, a):
self.a = a
def __len__(self):
return len(self.a)
def __getitem__(self, i):
return self.a[i]
┏━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━━━┓
┃ │ Iterable │ Collection │ Sequence │ abc.Sequence ┃
┠────────────┼────────────┼────────────┼────────────┼──────────────┨
┃ iter() │ ! │ ! │ ✓ │ ✓ ┃
┃ contains() │ ✓ │ ✓ │ ✓ │ ✓ ┃
┃ len() │ │ ! │ ! │ ! ┃
┃ getitem() │ │ │ ! │ ! ┃
┃ reversed() │ │ │ ✓ │ ✓ ┃
┃ index() │ │ │ │ ✓ ┃
┃ count() │ │ │ │ ✓ ┃
┗━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━━━┛
Other ABCs that generate missing methods are: MutableSequence, Set, MutableSet,
Mapping and MutableMapping.
Names of their required methods are stored in '<abc>.__abstractmethods__'.
# Enum
class <enum_name>(Enum):
<member_name_1> = <value_1>
<member_name_2> = <value_2_a>, <value_2_b>
<member_name_3> = auto()
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 19/51
7/5/2020 Comprehensive Python Cheatsheet
list_of_members = list(<enum>)
member_names = [a.name for a in <enum>]
member_values = [a.value for a in <enum>]
random_member = random.choice(list(<enum>))
def get_next_member(member):
members = list(member.__class__)
index = (members.index(member) + 1) % len(members)
return members[index]
Inline
Another solution in this particular case is to use built-in functions and_() and or_() from
the module operator.
# Exceptions
Basic Example
try:
<code>
except <exception>:
<code>
Complex Example
try:
<code_1>
except <exception_a>:
<code_2_a>
except <exception_b>:
<code_2_b>
else:
<code_2_c>
finally:
<code_3>
Code inside the 'else' block will only be executed if 'try' block had no exception.
Code inside the 'finally' block will always be executed.
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 20/51
7/5/2020 Comprehensive Python Cheatsheet
Catching Exceptions
except <exception>:
except <exception> as <name>:
except (<exception>, ...):
except (<exception>, ...) as <name>:
Raising Exceptions
raise <exception>
raise <exception>()
raise <exception>(<el> [, ...])
Exception Object
arguments = <name>.args
exc_type = <name>.__class__
filename = <name>.__traceback__.tb_frame.f_code.co_filename
func_name = <name>.__traceback__.tb_frame.f_code.co_name
line = linecache.getline(filename, <name>.__traceback__.tb_lineno)
error_msg = traceback.format_exception(exc_type, <name>, <name>.__traceback__)
Built-in Exceptions
BaseException
├── SystemExit # Raised by the sys.exit() function.
├── KeyboardInterrupt # Raised when the user hits the interrupt key (ctrl-c).
└── Exception # User-defined exceptions should be derived from this class.
├── ArithmeticError # Base class for arithmetic errors.
│ └── ZeroDivisionError # Raised when dividing by zero.
├── AttributeError # Raised when an attribute is missing.
├── EOFError # Raised by input() when it hits end-of-file condition.
├── LookupError # Raised when a look-up on a collection fails.
│ ├── IndexError # Raised when a sequence index is out of range.
│ └── KeyError # Raised when a dictionary key or set element is not found.
├── NameError # Raised when a variable name is not found.
├── OSError # Failures such as “file not found” or “disk full”.
│ └── FileNotFoundError # When a file or directory is requested but doesn't exist.
├── RuntimeError # Raised by errors that don't fall in other categories.
│ └── RecursionError # Raised when the maximum recursion depth is exceeded.
├── StopIteration # Raised by next() when run on an empty iterator.
├── TypeError # Raised when an argument is of wrong type.
└── ValueError # When an argument is of right type but inappropriate value.
└── UnicodeError # Raised when encoding/decoding strings to/from bytes fails.
┏━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┓
┃ │ list │ dict │ set ┃
┠───────────┼────────────┼────────────┼────────────┨
┃ getitem() │ IndexError │ KeyError │ ┃
┃ pop() │ IndexError │ KeyError │ KeyError ┃
┃ remove() │ ValueError │ │ KeyError ┃
┃ index() │ ValueError │ │ ┃
┗━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 21/51
7/5/2020 Comprehensive Python Cheatsheet
Useful built-in exceptions:
class MyError(Exception):
pass
class MyInputError(MyError):
pass
# Exit
Exits the interpreter by raising SystemExit exception.
import sys
sys.exit() # Exits with exit code 0 (success).
sys.exit(<el>) # Prints to stderr and exits with 1.
sys.exit(<int>) # Exits with passed exit code.
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 22/51
7/5/2020 Comprehensive Python Cheatsheet
Pretty Print
# Input
Reads a line from user input or pipe if present.
<str> = input(prompt=None)
import sys
script_name = sys.argv[0]
arguments = sys.argv[1:]
Argument Parser
# Open
Opens the le and returns a corresponding le object.
'encoding=None' means that the default encoding is used, which is platform dependent.
Best practice is to use 'encoding="utf-8"' whenever possible.
'newline=None' means all different end of line combinations are converted to '\n' on
read, while on write all '\n' characters are converted to system's default line separator.
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 23/51
7/5/2020 Comprehensive Python Cheatsheet
'newline=""' means no conversions take place, but input is still broken into chunks by
readline() and readlines() on either '\n', '\r' or '\r\n'.
Modes
Exceptions
File Object
def read_file(filename):
with open(filename, encoding='utf-8') as file:
return file.readlines()
# Path
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 24/51
7/5/2020 Comprehensive Python Cheatsheet
<str> = path.basename(<path>) # Returns final component of the path.
<str> = path.dirname(<path>) # Returns path without the final component.
<tup.> = path.splitext(<path>) # Splits on last period of the final component.
DirEntry
Using scandir() instead of listdir() can signi cantly increase the performance of code that also
needs le type information.
Path Object
# OS Commands
Files and Directories
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 25/51
7/5/2020 Comprehensive Python Cheatsheet
os.rename(from, to) # Renames/moves the file or directory.
os.replace(from, to) # Same, but overwrites 'to' if it exists.
Shell Commands
import os
<str> = os.popen('<shell_command>').read()
Sends '1 + 1' to the basic calculator and captures its output:
Sends test.in to the basic calculator running in standard mode and saves its output to test.out:
# JSON
Text le format for storing collections of strings and numbers.
import json
<str> = json.dumps(<object>, ensure_ascii=True, indent=None)
<object> = json.loads(<str>)
def read_json_file(filename):
with open(filename, encoding='utf-8') as file:
return json.load(file)
# Pickle
Binary le format for storing objects.
import pickle
<bytes> = pickle.dumps(<object>)
<object> = pickle.loads(<bytes>)
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 26/51
7/5/2020 Comprehensive Python Cheatsheet
def read_pickle_file(filename):
with open(filename, 'rb') as file:
return pickle.load(file)
# CSV
Text le format for storing spreadsheets.
import csv
Read
File must be opened with 'newline=""' argument, or newlines embedded inside quoted
elds will not be interpreted correctly!
Write
File must be opened with 'newline=""' argument, or '\r' will be added in front of every
'\n' on platforms that use '\r\n' line endings!
Parameters
Dialects
┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┓
┃ │ excel │ excel-tab │ unix ┃
┠──────────────────┼──────────────┼──────────────┼──────────────┨
┃ delimiter │ ',' │ '\t' │ ',' ┃
┃ quotechar │ '"' │ '"' │ '"' ┃
┃ doublequote │ True │ True │ True ┃
┃ skipinitialspace │ False │ False │ False ┃
┃ lineterminator │ '\r\n' │ '\r\n' │ '\n' ┃
┃ quoting │ 0 │ 0 │ 1 ┃
┃ escapechar │ None │ None │ None ┃
┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┛
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 27/51
7/5/2020 Comprehensive Python Cheatsheet
def read_csv_file(filename):
with open(filename, encoding='utf-8', newline='') as file:
return list(csv.reader(file))
# SQLite
Server-less database engine that stores each database into a separate le.
Connect
Opens a connection to the database le. Creates a new le if path doesn't exist.
import sqlite3
<con> = sqlite3.connect('<path>') # Also ':memory:'.
<con>.close()
Read
Write
<con>.execute('<query>')
<con>.commit()
Or:
with <con>:
<con>.execute('<query>')
Placeholders
Passed values can be of type str, int, oat, bytes, None, bool, datetime.date or
datetime.datetme.
Bools will be stored and returned as ints and dates as ISO formatted strings.
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 28/51
7/5/2020 Comprehensive Python Cheatsheet
Example
In this example values are not actually saved because 'con.commit()' is omitted!
MySQL
# Bytes
Bytes object is an immutable sequence of single bytes. Mutable version is called bytearray.
Encode
Decode
def read_bytes(filename):
with open(filename, 'rb') as file:
return file.read()
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 29/51
7/5/2020 Comprehensive Python Cheatsheet
# Struct
Module that performs conversions between a sequence of numbers and a bytes object.
Machine’s native type sizes and byte order are used by default.
Example
>>> pack('>hhl', 1, 2, 3)
b'\x00\x01\x00\x02\x00\x00\x00\x03'
>>> unpack('>hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
(1, 2, 3)
Format
Integer types. Use a capital letter for unsigned type. Standard sizes are in brackets:
# Array
List that can only hold numbers of a prede ned type. Available types and their sizes in bytes
are listed above.
# Memory View
A sequence object that points to the memory of another object.
Each element can reference a single or multiple consecutive bytes, depending on format.
Order and number of elements can be changed with slicing.
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 30/51
7/5/2020 Comprehensive Python Cheatsheet
Decode
# Deque
A thread-safe list with ef cient appends and pops from either side. Pronounced "deck".
# Threading
CPython interpreter can only run a single thread at a time.
That is why using multiple threads won't result in a faster execution, unless at least one
of the threads contains an I/O operation.
Thread
Lock
<lock> = RLock()
<lock>.acquire() # Waits for lock to be available.
<lock>.release() # Makes the lock available again.
Or:
lock = RLock()
with lock:
...
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 31/51
7/5/2020 Comprehensive Python Cheatsheet
Future:
Queue
# Operator
Module of functions that provide the functionality of operators.
from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs
from operator import eq, ne, lt, le, gt, ge
from operator import and_, or_, not_
from operator import itemgetter, attrgetter, methodcaller
import operator as op
elementwise_sum = map(op.add, list_a, list_b)
sorted_by_second = sorted(<collection>, key=op.itemgetter(1))
sorted_by_both = sorted(<collection>, key=op.itemgetter(1, 0))
product_of_elems = functools.reduce(op.mul, <collection>)
LogicOp = enum.Enum('LogicOp', {'AND': op.and_, 'OR' : op.or_})
last_el = op.methodcaller('pop')(<list>)
# Introspection
Inspecting code at runtime.
Variables
Attributes
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 32/51
7/5/2020 Comprehensive Python Cheatsheet
Parameters
# Metaprograming
Code that generates code.
Type
Type is the root class. If only passed an object it returns its type (class). Otherwise it creates a
new class.
Meta Class
Or:
class MyMetaClass(type):
def __new__(cls, name, parents, attrs):
attrs['a'] = 'abcde'
return type.__new__(cls, name, parents, attrs)
New() is a class method that gets called before init(). If it returns an instance of its class,
then that instance gets passed to init() as a 'self' argument.
It receives the same arguments as init(), except for the rst one that speci es the desired
type of the returned instance (MyMetaClass in our case).
Like in our case, new() can also be called directly, usually from a new() method of a child
class (def __new__(cls): return super().__new__(cls)).
The only difference between the examples above is that my_meta_class() returns a class of
type type, while MyMetaClass() returns a class of type MyMetaClass.
Metaclass Attribute
Right before a class is created it checks if it has the 'metaclass' attribute de ned. If not, it
recursively checks if any of his parents has it de ned and eventually comes to type().
class MyClass(metaclass=MyMetaClass):
b = 12345
Type Diagram
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 33/51
7/5/2020 Comprehensive Python Cheatsheet
┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┓
┃ Classes │ Metaclasses ┃
┠─────────────┼─────────────┨
┃ MyClass ──→ MyMetaClass ┃
┃ │ ↓ ┃
┃ object ─────→ type ←╮ ┃
┃ │ ↑ ╰──╯ ┃
┃ str ──────────╯ ┃
┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┛
Inheritance Diagram
┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┓
┃ Classes │ Metaclasses ┃
┠─────────────┼─────────────┨
┃ MyClass │ MyMetaClass ┃
┃ ↓ │ ↓ ┃
┃ object ←───── type ┃
┃ ↑ │ ┃
┃ str │ ┃
┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┛
# Eval
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 34/51
7/5/2020 Comprehensive Python Cheatsheet
# Coroutines
Coroutines have a lot in common with threads, but unlike threads, they only give up
control when they call another coroutine and they don’t use as much memory.
Coroutine de nition starts with 'async' and its call with 'await'.
'asyncio.run(<coroutine>)' is the main entry point for asynchronous programs.
Functions wait(), gather() and as_completed() can be used when multiple coroutines need
to be started at the same time.
Asyncio module also provides its own Queue, Event, Lock and Semaphore classes.
Runs a terminal game where you control an asterisk that must avoid numbers:
def main(screen):
curses.curs_set(0) # Makes cursor invisible.
screen.nodelay(True) # Makes getch() non-blocking.
asyncio.run(main_coroutine(screen)) # Starts running asyncio code.
curses.wrapper(main)
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 35/51
7/5/2020 Comprehensive Python Cheatsheet
Libraries
# Progress Bar
# Plot
# Table
Prints a CSV le as an ASCII table:
# Curses
Clears the terminal, prints a message and waits for the ESC key press:
def main():
wrapper(draw)
def draw(screen):
curs_set(0) # Makes cursor invisible.
screen.nodelay(True) # Makes getch() non-blocking.
screen.clear()
screen.addstr(0, 0, 'Press ESC to quit.') # Coordinates are y, x.
while screen.getch() != ascii.ESC:
pass
def get_border(screen):
from collections import namedtuple
P = namedtuple('P', 'x y')
height, width = screen.getmaxyx()
return P(width-1, height-1)
if __name__ == '__main__':
main()
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 36/51
7/5/2020 Comprehensive Python Cheatsheet
# Logging
Exceptions
Exception description, stack trace and values of variables are appended automatically.
try:
...
except <exception>:
logger.exception('An error happened.')
Rotation
rotation=<int>|<datetime.timedelta>|<datetime.time>|<str>
Retention
retention=<int>|<datetime.timedelta>|<str>
# Scraping
Scrapes Python's URL, version number and logo from Wikipedia page:
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 37/51
7/5/2020 Comprehensive Python Cheatsheet
# Web
Run
Static Request
@route('/img/<image>')
def send_image(image):
return static_file(image, 'img_dir/', mimetype='image/png')
Dynamic Request
@route('/<sport>')
def send_page(sport):
return template('<h1>{{title}}</h1>', title=sport)
REST Request
@post('/odds/<sport>')
def odds_handler(sport):
team = request.forms.get('team')
home_odds, away_odds = 2.44, 3.29
response.headers['Content-Type'] = 'application/json'
response.headers['Cache-Control'] = 'no-cache'
return json.dumps([team, home_odds, away_odds])
Test:
# Pro ling
Stopwatch
High performance:
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 38/51
7/5/2020 Comprehensive Python Cheatsheet
Timing a Snippet
Call Graph
# NumPy
Array manipulation mini-language. It can run up to one hundred times faster than the
equivalent Python code.
<array> = np.array(<list>)
<array> = np.arange(from_inclusive, to_exclusive, ±step_size)
<array> = np.ones(<shape>)
<array> = np.random.randint(from_inclusive, to_exclusive, <shape>)
<array>.shape = <shape>
<view> = <array>.reshape(<shape>)
<view> = np.broadcast_to(<array>, <shape>)
<array> = <array>.sum(axis)
indexes = <array>.argmin(axis)
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 39/51
7/5/2020 Comprehensive Python Cheatsheet
Indexing
If row and column indexes differ in shape, they are combined with broadcasting.
Broadcasting
Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes
and/or dimensions.
1. If array shapes differ in length, left-pad the shorter shape with ones:
2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements:
left = [[0.1, 0.1, 0.1], [0.6, 0.6, 0.6], [0.8, 0.8, 0.8]] # Shape: (3, 3) <- !
right = [[0.1, 0.6, 0.8], [0.1, 0.6, 0.8], [0.1, 0.6, 0.8]] # Shape: (3, 3) <- !
Example
For each point returns index of its nearest point ([0.1, 0.6, 0.8] => [1, 2, 1]):
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 40/51
7/5/2020 Comprehensive Python Cheatsheet
# Image
Modes
'1' - 1-bit pixels, black and white, stored with one pixel per byte.
'L' - 8-bit pixels, greyscale.
'RGB' - 3x8-bit pixels, true color.
'RGBA' - 4x8-bit pixels, true color with transparency mask.
'HSV' - 3x8-bit pixels, Hue, Saturation, Value color space.
Examples
Drawing
<ImageDraw> = ImageDraw.Draw(<Image>)
<ImageDraw>.point((x, y), fill=None)
<ImageDraw>.line((x1, y1, x2, y2 [, ...]), fill=None, width=0, joint=None)
<ImageDraw>.arc((x1, y1, x2, y2), from_deg, to_deg, fill=None, width=0)
<ImageDraw>.rectangle((x1, y1, x2, y2), fill=None, outline=None, width=0)
<ImageDraw>.polygon((x1, y1, x2, y2 [, ...]), fill=None, outline=None)
<ImageDraw>.ellipse((x1, y1, x2, y2), fill=None, outline=None, width=0)
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 41/51
7/5/2020 Comprehensive Python Cheatsheet
# Animation
Creates a GIF of a bouncing ball:
# Audio
import wave
Bytes object contains a sequence of frames, each consisting of one or more samples.
In a stereo signal, the rst sample of a frame belongs to the left channel.
Each sample consists of one or more bytes that, when converted to an integer, indicate
the displacement of a speaker membrane at a given moment.
If sample width is one, then the integer should be encoded unsigned.
For all other sizes, the integer should be encoded signed with little-endian byte order.
Sample Values
┏━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━┯━━━━━━━━━━━━━┓
┃ sampwidth │ min │ zero │ max ┃
┠───────────┼─────────────┼──────┼─────────────┨
┃ 1 │ 0 │ 128 │ 255 ┃
┃ 2 │ -32768 │ 0 │ 32767 ┃
┃ 3 │ -8388608 │ 0 │ 8388607 ┃
┃ 4 │ -2147483648 │ 0 │ 2147483647 ┃
┗━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━┷━━━━━━━━━━━━━┛
def read_wav_file(filename):
def get_int(a_bytes):
an_int = int.from_bytes(a_bytes, 'little', signed=width!=1)
return an_int - 128 * (width == 1)
with wave.open(filename, 'rb') as file:
width = file.getsampwidth()
frames = file.readframes(-1)
byte_samples = (frames[i: i + width] for i in range(0, len(frames), width))
return [get_int(b) / pow(2, width * 8 - 1) for b in byte_samples]
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 42/51
7/5/2020 Comprehensive Python Cheatsheet
Examples
Text to Speech
# Synthesizer
Plays Popcorn by Gershon Kingsley:
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 43/51
7/5/2020 Comprehensive Python Cheatsheet
# Pygame
Basic Example
Rectangle
Surface
Font
Sound
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 44/51
7/5/2020 Comprehensive Python Cheatsheet
def main():
def get_screen():
pygame.init()
return pygame.display.set_mode(2 * [SIZE*16])
def get_images():
url = 'https://gto76.github.io/python-cheatsheet/web/mario_bros.png'
img = pygame.image.load(io.BytesIO(urllib.request.urlopen(url).read()))
return [img.subsurface(get_rect(x, 0)) for x in range(img.get_width() // 16)]
def get_mario():
Mario = dataclasses.make_dataclass('Mario', 'rect spd facing_left frame_cycle'.split())
return Mario(get_rect(1, 1), P(0, 0), False, it.cycle(range(3)))
def get_tiles():
positions = [p for p in it.product(range(SIZE), repeat=2) if {*p} & {0, SIZE-1}] + \
[(randint(1, SIZE-2), randint(2, SIZE-2)) for _ in range(SIZE**2 // 10)]
return [get_rect(*p) for p in positions]
def get_rect(x, y):
return pygame.Rect(x*16, y*16, 16, 16)
run(get_screen(), get_images(), get_mario(), get_tiles())
if __name__ == '__main__':
main()
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 45/51
7/5/2020 Comprehensive Python Cheatsheet
# Pandas
Series
┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓
┃ │ 'sum' │ ['sum'] │ {'s': 'sum'} ┃
┠─────────────┼─────────────┼─────────────┼───────────────┨
┃ sr.apply(…) │ 3 │ sum 3 │ s 3 ┃
┃ sr.agg(…) │ │ │ ┃
┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛
┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓
┃ │ 'rank' │ ['rank'] │ {'r': 'rank'} ┃
┠─────────────┼─────────────┼─────────────┼───────────────┨
┃ sr.apply(…) │ │ rank │ ┃
┃ sr.agg(…) │ x 1 │ x 1 │ r x 1 ┃
┃ sr.trans(…) │ y 2 │ y 2 │ y 2 ┃
┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛
Last result has a hierarchical index. Use '<Sr>[key_1, key_2]' to get its values.
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 46/51
7/5/2020 Comprehensive Python Cheatsheet
DataFrame
┏━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ how/join │ 'outer' │ 'inner' │ 'left' │ description ┃
┠────────────────────────┼───────────────┼────────────┼────────────┼──────────────────────────┨
┃ l.merge(r, on='y', │ x y z │ x y z │ x y z │ Joins/merges on column. ┃
┃ how=…) │ 0 1 2 . │ 3 4 5 │ 1 2 . │ Also accepts left_on and ┃
┃ │ 1 3 4 5 │ │ 3 4 5 │ right_on parameters. ┃
┃ │ 2 . 6 7 │ │ │ Uses 'inner' by default. ┃
┠────────────────────────┼───────────────┼────────────┼────────────┼──────────────────────────┨
┃ l.join(r, lsuffix='l', │ x yl yr z │ │ x yl yr z │ Joins/merges on row keys.┃
┃ rsuffix='r', │ a 1 2 . . │ x yl yr z │ 1 2 . . │ Uses 'left' by default. ┃
┃ how=…) │ b 3 4 4 5 │ 3 4 4 5 │ 3 4 4 5 │ ┃
┃ │ c . . 6 7 │ │ │ ┃
┠────────────────────────┼───────────────┼────────────┼────────────┼──────────────────────────┨
┃ pd.concat([l, r], │ x y z │ y │ │ Adds rows at the bottom. ┃
┃ axis=0, │ a 1 2 . │ 2 │ │ Uses 'outer' by default. ┃
┃ join=…) │ b 3 4 . │ 4 │ │ By default works the ┃
┃ │ b . 4 5 │ 4 │ │ same as `l.append(r)`. ┃
┃ │ c . 6 7 │ 6 │ │ ┃
┠────────────────────────┼───────────────┼────────────┼────────────┼──────────────────────────┨
┃ pd.concat([l, r], │ x y y z │ │ │ Adds columns at the ┃
┃ axis=1, │ a 1 2 . . │ x y y z │ │ right end. ┃
┃ join=…) │ b 3 4 4 5 │ 3 4 4 5 │ │ Uses 'outer' by default. ┃
┃ │ c . . 6 7 │ │ │ ┃
┠────────────────────────┼───────────────┼────────────┼────────────┼──────────────────────────┨
┃ l.combine_first(r) │ x y z │ │ │ Adds missing rows and ┃
┃ │ a 1 2 . │ │ │ columns. ┃
┃ │ b 3 4 5 │ │ │ ┃
┃ │ c . 6 7 │ │ │ ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━┛
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 47/51
7/5/2020 Comprehensive Python Cheatsheet
Aggregate, Transform, Map:
All operations operate on columns by default. Use 'axis=1' parameter to process the
rows instead.
┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓
┃ │ 'sum' │ ['sum'] │ {'x': 'sum'} ┃
┠─────────────┼─────────────┼─────────────┼───────────────┨
┃ df.apply(…) │ │ x y │ ┃
┃ df.agg(…) │ x 4 │ sum 4 6 │ x 4 ┃
┃ │ y 6 │ │ ┃
┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛
┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓
┃ │ 'rank' │ ['rank'] │ {'x': 'rank'} ┃
┠─────────────┼─────────────┼─────────────┼───────────────┨
┃ df.apply(…) │ x y │ x y │ x ┃
┃ df.agg(…) │ a 1 1 │ rank rank │ a 1 ┃
┃ df.trans(…) │ b 2 2 │ a 1 1 │ b 2 ┃
┃ │ │ b 2 2 │ ┃
┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛
Encode, Decode:
<DF> = pd.read_json/html('<str/path/url>')
<DF> = pd.read_csv/pickle/excel('<path/url>')
<DF> = pd.read_sql('<query>', <connection>)
<DF> = pd.read_clipboard()
<dict> = <DF>.to_dict(['d/l/s/sp/r/i'])
<str> = <DF>.to_json/html/csv/markdown/latex([<path>])
<DF>.to_pickle/excel(<path>)
<DF>.to_sql('<table_name>', <connection>)
GroupBy
Object that groups together rows of a dataframe based on the value of the passed column.
┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓
┃ │ 'sum' │ 'rank' │ ['rank'] │ {'x': 'rank'} ┃
┠─────────────┼─────────────┼─────────────┼─────────────┼───────────────┨
┃ gb.agg(…) │ x y │ x y │ x y │ x ┃
┃ │ z │ a 1 1 │ rank rank │ a 1 ┃
┃ │ 3 1 2 │ b 1 1 │ a 1 1 │ b 1 ┃
┃ │ 6 11 13 │ c 2 2 │ b 1 1 │ c 2 ┃
┃ │ │ │ c 2 2 │ ┃
┠─────────────┼─────────────┼─────────────┼─────────────┼───────────────┨
┃ gb.trans(…) │ x y │ x y │ │ ┃
┃ │ a 1 2 │ a 1 1 │ │ ┃
┃ │ b 11 13 │ b 1 1 │ │ ┃
┃ │ c 11 13 │ c 1 1 │ │ ┃
┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛
Rolling
# Plotly
Covid Deaths by Continent
Continent
250 Africa
Asia
Europe
200 North America
Total Deaths per Million
Oceania
South America
150
100
50
covid = pd.read_csv('https://covid.ourworldindata.org/data/owid-covid-data.csv',
usecols=['iso_code', 'date', 'total_deaths', 'population'])
continents = pd.read_csv('https://datahub.io/JohnSnowLabs/country-and-continent-codes-' + \
'list/r/country-and-continent-codes-list-csv.csv',
usecols=['Three_Letter_Country_Code', 'Continent_Name'])
df = pd.merge(covid, continents, left_on='iso_code', right_on='Three_Letter_Country_Code')
df = df.groupby(['Continent_Name', 'date']).sum().reset_index()
df['Total Deaths per Million'] = df.total_deaths * 1e6 / df.population
df = df[('2020-03-14' < df.date) & (df.date < '2020-06-25')]
df = df.rename({'date': 'Date', 'Continent_Name': 'Continent'}, axis='columns')
plotly.express.line(df, x='Date', y='Total Deaths per Million', color='Continent').show()
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 49/51
7/5/2020 Comprehensive Python Cheatsheet
Con rmed Covid Cases, Dow Jones, Gold, and Bitcoin Price
Dow Jones
100 Gold
Bitcoin
Total Cases
15M
80
Total Cases
60
10M
%
40
5M
20
0 0
Mar 1 Mar 15 Mar 29 Apr 12 Apr 26 May 10 May 24 Jun 7 Jun 21
2020
def main():
display_data(wrangle_data(*scrape_data()))
def scrape_data():
def scrape_yahoo(id_):
BASE_URL = 'https://query1.finance.yahoo.com/v7/finance/download/'
now = int(datetime.datetime.now().timestamp())
url = f'{BASE_URL}{id_}?period1=1579651200&period2={now}&interval=1d&events=history'
return pandas.read_csv(url, usecols=['Date', 'Close']).set_index('Date').Close
covid = pd.read_csv('https://covid.ourworldindata.org/data/owid-covid-data.csv',
usecols=['date', 'total_cases'])
covid = covid.groupby('date').sum()
dow, gold, bitcoin = [scrape_yahoo(id_) for id_ in ('^DJI', 'GC=F', 'BTC-USD')]
dow.name, gold.name, bitcoin.name = 'Dow Jones', 'Gold', 'Bitcoin'
return covid, dow, gold, bitcoin
def display_data(df):
def get_trace(col_name):
return go.Scatter(x=df.index, y=df[col_name], name=col_name, yaxis='y2')
traces = [get_trace(col_name) for col_name in df.columns[1:]]
traces.append(go.Scatter(x=df.index, y=df.total_cases, name='Total Cases', yaxis='y1'))
figure = go.Figure()
figure.add_traces(traces)
figure.update_layout(
yaxis1=dict(title='Total Cases', rangemode='tozero'),
yaxis2=dict(title='%', rangemode='tozero', overlaying='y', side='right'),
legend=dict(x=1.1)
).show()
if __name__ == '__main__':
main()
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 50/51
7/5/2020 Comprehensive Python Cheatsheet
# Cython
Library that compiles Python code into C.
De nitions
All 'cdef' de nitions are optional, but they contribute to the speed-up.
Script needs to be saved with a 'pyx' extension.
#!/usr/bin/env python3
#
# Usage: .py
#
def main():
pass
###
## UTIL
#
def read_file(filename):
with open(filename, encoding='utf-8') as file:
return file.readlines()
if __name__ == '__main__':
main()
https://gto76.github.io/python-cheatsheet/?utm_campaign=Data_Elixir&utm_medium=rss&utm_source=Data_Elixir_292#list 51/51