Python For Data Science
Python For Data Science
L I STS len(my_set) - Returns the number of objects in now - wks4 - Return a datetime object
l.pop(3) - Returns the fourth item from l and my_set (or, the number of unique values from l) representing the time 4 weeks prior to now
deletes it from the list a in my_set - Returns True if the value a exists in newyear_2020 = dt.datetime(year=2020,
l.remove(x) - Removes the first item in l that is my_set month=12, day=31) - Assign a datetime
equal to x object representing December 25, 2020 to
l.reverse() - Reverses the order of the items in l REGULAR EXPRESSIONS newyear_2020
l[1::2] - Returns every second item from l, import re - Import the Regular Expressions module newyear_2020.strftime("%A, %b %d, %Y")
commencing from the 1st item re.search("abc",s) - Returns a match object if - Returns "Thursday, Dec 31, 2020"
l[-5:] - Returns the last 5 items from l specific axis the regex "abc" is found in s, otherwise None dt.datetime.strptime('Dec 31, 2020',"%b
re.sub("abc","xyz",s) - Returns a string where %d, %Y") - Return a datetime object
ST R I N G S all instances matching regex "abc" are replaced representing December 31, 2020
s.lower() - Returns a lowercase version of s by "xyz"
s.title() - Returns s with the first letter of every RANDOM
word capitalized L I ST C O M P R E H E N S I O N import random - Import the random module
"23".zfill(4) - Returns "0023" by left-filling the A one-line expression of a for loop random.random() - Returns a random float
string with 0’s to make it’s length 4. [i ** 2 for i in range(10)] - Returns a list of between 0.0 and 1.0
s.splitlines() - Returns a list by splitting the the squares of values from 0 to 9 random.randint(0,10) - Returns a random
string on any newline characters. [s.lower() for s in l_strings] - Returns the integer between 0 and 10
Python strings share some common methods with lists list l_strings, with each item having had the random.choice(l) - Returns a random item from
s[:5] - Returns the first 5 characters of s .lower() method applied the list l
"fri" + "end" - Returns "friend" [i for i in l_floats if i < 0.5] - Returns
"end" in s - Returns True if the substring "end" the items from l_floats that are less than 0.5 COUNTER
is found in s from collections import Counter - Import the
F U N C T I O N S F O R LO O P I N G Counter class
RANGE for i, value in enumerate(l): c = Counter(l) - Assign a Counter (dict-like)
Range objects are useful for creating sequences of print("The value of item {} is {}". object with the counts of each unique item from
integers for looping. format(i,value)) l, to c
range(5) - Returns a sequence from 0 to 4 - Iterate over the list l, printing the index location c.most_common(3) - Return the 3 most common
range(2000,2018) - Returns a sequence from 2000 of each item and its value items from l
to 2017 for one, two in zip(l_one,l_two):
range(0,11,2) - Returns a sequence from 0 to 10, print("one: {}, two: {}".format(one,two)) T RY/ E XC E P T
with each item incrementing by 2 - Iterate over two lists, l_one and l_two and print Catch and deal with Errors
range(0,-10,-1) - Returns a sequence from 0 to -9 each value l_ints = [1, 2, 3, "", 5] - Assign a list of
list(range(5)) - Returns a list from 0 to 4 while x < 10: integers with one missing value to l_ints
x += 1 l_floats = []
DICTIONARIES - Run the code in the body of the loop until the for i in l_ints:
max(d, key=d.get) - Return the key that value of x is no longer less than 10 try:
corresponds to the largest value in d l_floats.append(float(i))
min(d, key=d.get) - Return the key that DAT E T I M E except:
corresponds to the smallest value in d import datetime as dt - Import the datetime l_floats.append(i)
module - Convert each value of l_ints to a float, catching
S E TS now = dt.datetime.now() - Assign datetime and handling ValueError: could not convert
my_set = set(l) - Return a set object containing object representing the current time to now string to float: where values are missing.
the unique values from l wks4 = dt.datetime.timedelta(weeks=4)
- Assign a timedelta object representing a
timespan of 4 weeks to wks4
KEY IMPORTS
We’ll use shorthand in this cheat sheet Import these to start
arr - A numpy Array object import numpy as np
S P E C I A L C H A R AC T E R S \A | Matches the expression to its right at the (?:A) | Matches the expression as represented
^ | Matches the expression to its right at the absolute start of a string whether in single by A, but unlike (?PAB), it cannot be
start of a string. It matches every such or multi-line mode. retrieved afterwards.
instance before each \n in the string. \Z | Matches the expression to its left at the (?#...) | A comment. Contents are for us to
$ | Matches the expression to its left at the absolute end of a string whether in single read, not for matching.
end of a string. It matches every such or multi-line mode. A(?=B) | Lookahead assertion. This matches
instance before each \n in the string. the expression A only if it is followed by B.
. | Matches any character except line A(?!B) | Negative lookahead assertion. This
terminators like \n. S E TS matches the expression A only if it is not
\ | Escapes special characters or denotes [ ] | Contains a set of characters to match. followed by B.
character classes. [amk] | Matches either a, m, or k. It does not (?<=B)A | Positive lookbehind assertion.
A|B | Matches expression A or B. If A is match amk. This matches the expression A only if B
matched first, B is left untried. [a-z] | Matches any alphabet from a to z. is immediately to its left. This can only
+ | Greedily matches the expression to its left 1 [a\-z] | Matches a, -, or z. It matches - matched fixed length expressions.
or more times. because \ escapes it. (?<!B)A | Negative lookbehind assertion.
* | Greedily matches the expression to its left [a-] | Matches a or -, because - is not being This matches the expression A only if B is
0 or more times. used to indicate a series of characters. not immediately to its left. This can only
? | Greedily matches the expression to its left [-a] | As above, matches a or -. matched fixed length expressions.
0 or 1 times. But if ? is added to qualifiers [a-z0-9] | Matches characters from a to z (?P=name) | Matches the expression matched
(+, *, and ? itself) it will perform matches in and also from 0 to 9. by an earlier group named “name”.
a non-greedy manner. [(+*)] | Special characters become literal (...)\1 | The number 1 corresponds to
{m} | Matches the expression to its left m inside a set, so this matches (, +, *, and ). the first group to be matched. If we want
times, and not less. [^ab5] | Adding ^ excludes any character in to match more instances of the same
{m,n} | Matches the expression to its left m to the set. Here, it matches characters that are expression, simply use its number instead of
n times, and not less. not a, b, or 5. writing out the whole expression again. We
{m,n}? | Matches the expression to its left m can use from 1 up to 99 such groups and
times, and ignores n. See ? above. their corresponding numbers.
GROUPS
( ) | Matches the expression inside the
C H A R AC T E R C L AS S E S parentheses and groups it. POPULAR PYTHON RE MODULE
( A. K.A. S P E C I A L S E Q U E N C E S) (?) | Inside parentheses like this, ? acts as an FUNCTIONS
\w | Matches alphanumeric characters, which extension notation. Its meaning depends on re.findall(A, B) | Matches all instances
means a-z, A-Z, and 0-9. It also matches the character immediately to its right. of an expression A in a string B and returns
the underscore, _. (?PAB) | Matches the expression AB, and it them in a list.
\d | Matches digits, which means 0-9. can be accessed with the group name. re.search(A, B) | Matches the first instance
\D | Matches any non-digits. (?aiLmsux) | Here, a, i, L, m, s, u, and x are of an expression A in a string B, and returns
\s | Matches whitespace characters, which flags: it as a re match object.
include the \t, \n, \r, and space characters. a — Matches ASCII only re.split(A, B) | Split a string B into a list
\S | Matches non-whitespace characters. i — Ignore case using the delimiter A.
\b | Matches the boundary (or empty string) L — Locale dependent re.sub(A, B, C) | Replace A with B in the
at the start and end of a word, that is, m — Multi-line string C.
between \w and \W. s — Matches all
\B | Matches where \b does not, that is, the u — Matches unicode
boundary of \w characters. x — Verbose