Slide 1

Slide 1 text

No content

Slide 2

Slide 2 text

DATAFY ALL THE THINGS Max Humber

Slide 3

Slide 3 text

DATAFY ALL THE THINGS Max Humber

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

Creator Data Creationism

Slide 6

Slide 6 text

Data is everywhere. And it’s everything (if you’re creative)! So it makes me so sad to see Iris and Titanic in every blog, tutorial and book on data science and machine learning. In DATAFY ALL THE THINGS I’ll empower you to curate and create your own data sets (so that we can all finally let Iris die). You’ll learn how to parse unstructured text, harvest data from interesting websites and public APIs and about capturing and dealing with sensor data. Examples in this talk will be provided and written in python and will rely on requests, beautifulsoup, mechanicalsoup, pandas and some 3.6+ magic!

Slide 7

Slide 7 text

No content

Slide 8

Slide 8 text

No content

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

No content

Slide 11

Slide 11 text

No content

Slide 12

Slide 12 text

No content

Slide 13

Slide 13 text

No content

Slide 14

Slide 14 text

…Who hasn’t stared at an iris plant and gone crazy trying to decide whether it’s an iris setosa, versicolor, or maybe even virginica? It’s the stuff that keeps you up at night for days at a time. Luckily, the iris dataset makes that super easy. All you have to do is measure the length and width of your particular iris’s petal and sepal, and you’re ready to rock! What’s that, you still can’t decide because the classes overlap? Well, but at least now you have data!

Slide 15

Slide 15 text

Iris Bespoke data

Slide 16

Slide 16 text

Iris Bespoke data

Slide 17

Slide 17 text

This presentation…

Slide 18

Slide 18 text

capture curate create

Slide 19

Slide 19 text

capture curate create

Slide 20

Slide 20 text

No content

Slide 21

Slide 21 text

pd.DataFrame()

Slide 22

Slide 22 text

import pandas as pd data = [ ['conference', 'month', 'attendees'], ['ODSC', 'May', 5000], ['PyData', 'June', 1500], ['PyCon', 'May', 3000], ['useR!', 'July', 2000], ['Strata', 'August', 2500] ] df = pd.DataFrame(data, columns=data.pop(0))

Slide 23

Slide 23 text

import pandas as pd data = [ ['conference', 'month', 'attendees'], ['ODSC', 'May', 5000], ['PyData', 'June', 1500], ['PyCon', 'May', 3000], ['useR!', 'July', 2000], ['Strata', 'August', 2500] ] df = pd.DataFrame(data, columns=data.pop(0))

Slide 24

Slide 24 text

import pandas as pd data = [ ['conference', 'month', 'attendees'], ['ODSC', 'May', 5000], ['PyData', 'June', 1500], ['PyCon', 'May', 3000], ['useR!', 'July', 2000], ['Strata', 'August', 2500] ] df = pd.DataFrame(data, columns=data.pop(0))

Slide 25

Slide 25 text

data = { 'package': ['requests', 'pandas', 'Keras', 'mummify'], 'installs': [4000000, 9000000, 875000, 1200] } df = pd.DataFrame(data)

Slide 26

Slide 26 text

data = { 'package': ['requests', 'pandas', 'Keras', 'mummify'], 'installs': [4000000, 9000000, 875000, 1200] } df = pd.DataFrame(data)

Slide 27

Slide 27 text

df = pd.DataFrame([ {'artist': 'Bino', 'plays': 100_000}, {'artist': 'Drake', 'plays': 1_000}, {'artist': 'ODESZA', 'plays': 10_000}, {'artist': 'Brasstracks', 'plays': 100} ])

Slide 28

Slide 28 text

df = pd.DataFrame([ {'artist': 'Bino', 'plays': 100_000}, {'artist': 'Drake', 'plays': 1_000}, {'artist': 'ODESZA', 'plays': 10_000}, {'artist': 'Brasstracks', 'plays': 100} ])

Slide 29

Slide 29 text

df = pd.DataFrame([ {'artist': 'Bino', 'plays': 100_000}, {'artist': 'Drake', 'plays': 1_000}, {'artist': 'ODESZA', 'plays': 10_000}, {'artist': 'Brasstracks', 'plays': 100} ]) PEP515

Slide 30

Slide 30 text

df = pd.DataFrame([ {'artist': 'Bino', 'plays': 100_000}, {'artist': 'Drake', 'plays': 1_000}, {'artist': 'ODESZA', 'plays': 10_000}, {'artist': 'Brasstracks', 'plays': 100} ]) PEP515

Slide 31

Slide 31 text

from io import StringIO csv = '''\ food,fat,carbs,protein avocado,0.15,0.09,0.02 orange,0.001,0.12,0.009 almond,0.49,0.22,0.21 steak,0.19,0,0.25 peas,0,0.04,0.1 ‘'' pd.read_csv(csv) df = pd.read_csv(StringIO(csv))

Slide 32

Slide 32 text

from io import StringIO csv = '''\ food,fat,carbs,protein avocado,0.15,0.09,0.02 orange,0.001,0.12,0.009 almond,0.49,0.22,0.21 steak,0.19,0,0.25 peas,0,0.04,0.1 ''' pd.read_csv(csv) df = pd.read_csv(StringIO(csv)) # --------------------------------------------------------------------------- # FileNotFoundError Traceback (most recent call last) # in () # ----> 1 pd.read_csv(csv) # # FileNotFoundError: File b'food,fat,carbs,protein\n...' does not exist

Slide 33

Slide 33 text

from io import StringIO csv = '''\ food,fat,carbs,protein avocado,0.15,0.09,0.02 orange,0.001,0.12,0.009 almond,0.49,0.22,0.21 steak,0.19,0,0.25 peas,0,0.04,0.1 ‘'' df = pd.read_csv(StringIO(csv)) df = pd.read_csv(StringIO(csv))

Slide 34

Slide 34 text

from io import StringIO csv = '''\ food,fat,carbs,protein avocado,0.15,0.09,0.02 orange,0.001,0.12,0.009 almond,0.49,0.22,0.21 steak,0.19,0,0.25 peas,0,0.04,0.1 ‘'' df = pd.read_csv(StringIO(csv)) df = pd.read_csv(StringIO(csv))

Slide 35

Slide 35 text

pd.DataFrame()

Slide 36

Slide 36 text

pd.DataFrame() faker

Slide 37

Slide 37 text

No content

Slide 38

Slide 38 text

# pip install Faker from faker import Faker fake = Faker() fake.name() fake.phone_number() fake.bs() fake.profile()

Slide 39

Slide 39 text

# pip install Faker from faker import Faker fake = Faker() fake.name() fake.phone_number() fake.bs() fake.profile()

Slide 40

Slide 40 text

# pip install Faker from faker import Faker fake = Faker() fake.name() fake.phone_number() fake.bs() fake.profile()

Slide 41

Slide 41 text

# pip install Faker from faker import Faker fake = Faker() fake.name() fake.phone_number() fake.bs() fake.profile()

Slide 42

Slide 42 text

# pip install Faker from faker import Faker fake = Faker() fake.name() fake.phone_number() fake.bs() fake.profile()

Slide 43

Slide 43 text

# pip install Faker from faker import Faker fake = Faker() fake.name() fake.phone_number() fake.bs() fake.profile()

Slide 44

Slide 44 text

# pip install Faker from faker import Faker fake = Faker() fake.name() fake.phone_number() fake.bs() fake.profile()

Slide 45

Slide 45 text

# pip install Faker from faker import Faker fake = Faker() fake.name() fake.phone_number() fake.bs() fake.profile()

Slide 46

Slide 46 text

# pip install Faker from faker import Faker fake = Faker() fake.name() fake.phone_number() fake.bs() fake.profile()

Slide 47

Slide 47 text

def create_rows(n=1): output = [{ 'created_at': fake.past_datetime(start_date='-365d'), 'name': fake.name(), 'occupation': fake.job(), 'address': fake.street_address(), 'credit_card': fake.credit_card_number(card_type='visa'), 'company_bs': fake.bs(), 'city': fake.city(), 'ssn': fake.ssn(), 'paragraph': fake.paragraph()} for x in range(n)] return pd.DataFrame(output) df = create_rows(10)

Slide 48

Slide 48 text

def create_rows(n=1): output = [{ 'created_at': fake.past_datetime(start_date='-365d'), 'name': fake.name(), 'occupation': fake.job(), 'address': fake.street_address(), 'credit_card': fake.credit_card_number(card_type='visa'), 'company_bs': fake.bs(), 'city': fake.city(), 'ssn': fake.ssn(), 'paragraph': fake.paragraph()} for x in range(n)] return pd.DataFrame(output) df = create_rows(10)

Slide 49

Slide 49 text

import pandas as pd import sqlite3 con = sqlite3.connect('data/fake.db') cur = con.cursor() df.to_sql(name='users', con=con, if_exists="append", index=True) pd.read_sql('select * from users', con)

Slide 50

Slide 50 text

import pandas as pd import sqlite3 con = sqlite3.connect('data/fake.db') cur = con.cursor() df.to_sql(name='users', con=con, if_exists="append", index=True) pd.read_sql('select * from users', con)

Slide 51

Slide 51 text

import pandas as pd import sqlite3 con = sqlite3.connect('data/fake.db') cur = con.cursor() df.to_sql(name='users', con=con, if_exists="append", index=True) pd.read_sql('select * from users', con)

Slide 52

Slide 52 text

import pandas as pd import sqlite3 con = sqlite3.connect('data/fake.db') cur = con.cursor() df.to_sql(name='users', con=con, if_exists="append", index=True) pd.read_sql('select * from users', con)

Slide 53

Slide 53 text

pd.DataFrame() faker

Slide 54

Slide 54 text

pd.DataFrame() faker sklearn

Slide 55

Slide 55 text

No content

Slide 56

Slide 56 text

No content

Slide 57

Slide 57 text

import numpy as np import pandas as pd n = 100 rng = np.random.RandomState(1993) x = 0.2 * rng.rand(n) y = 31*x + 2.1 + rng.randn(n) df = pd.DataFrame({'x': x, 'y': y})

Slide 58

Slide 58 text

df = pd.DataFrame({'x': x, 'y': y}) import altair as alt (alt.Chart(df, background='white') .mark_circle(color='red', size=50) .encode( x='x', y='y' ) )

Slide 59

Slide 59 text

df = pd.DataFrame({'x': x, 'y': y}) import altair as alt (alt.Chart(df, background='white') .mark_circle(color='red', size=50) .encode( x='x', y='y' ) )

Slide 60

Slide 60 text

df = pd.DataFrame({'x': x, 'y': y}) import altair as alt (alt.Chart(df, background='white') .mark_circle(color='red', size=50) .encode( x='x', y='y' ) )

Slide 61

Slide 61 text

Slide 62

Slide 62 text

Slide 63

Slide 63 text

No content

Slide 64

Slide 64 text

No content

Slide 65

Slide 65 text

No content

Slide 66

Slide 66 text

No content

Slide 67

Slide 67 text

No content

Slide 68

Slide 68 text

No content

Slide 69

Slide 69 text

No content

Slide 70

Slide 70 text

No content

Slide 71

Slide 71 text

No content

Slide 72

Slide 72 text

No content

Slide 73

Slide 73 text

No content

Slide 74

Slide 74 text

No content

Slide 75

Slide 75 text

No content

Slide 76

Slide 76 text

with open('data/clippings.txt', 'r', encoding='utf-8-sig') as f: contents = f.read().replace(u'\ufeff', '') lines = contents.rsplit('==========') store = {'author': [], 'title': [], 'quote': []} for line in lines: try: meta, quote = line.split(')\n- ', 1) title, author = meta.split(' (', 1) _, quote = quote.split('\n\n') store['author'].append(author.strip()) store['title'].append(title.strip()) store['quote'].append(quote.strip()) except ValueError: pass

Slide 77

Slide 77 text

with open('data/clippings.txt', 'r', encoding='utf-8-sig') as f: contents = f.read().replace(u'\ufeff', '') lines = contents.rsplit('==========') store = {'author': [], 'title': [], 'quote': []} for line in lines: try: meta, quote = line.split(')\n- ', 1) title, author = meta.split(' (', 1) _, quote = quote.split('\n\n') store['author'].append(author.strip()) store['title'].append(title.strip()) store['quote'].append(quote.strip()) except ValueError: pass

Slide 78

Slide 78 text

with open('data/clippings.txt', 'r', encoding='utf-8-sig') as f: contents = f.read().replace(u'\ufeff', '') lines = contents.rsplit('==========') store = {'author': [], 'title': [], 'quote': []} for line in lines: try: meta, quote = line.split(')\n- ', 1) title, author = meta.split(' (', 1) _, quote = quote.split('\n\n') store['author'].append(author.strip()) store['title'].append(title.strip()) store['quote'].append(quote.strip()) except ValueError: pass

Slide 79

Slide 79 text

No content

Slide 80

Slide 80 text

import markovify import pandas as pd df = pd.read_csv('data/highlights.csv') text = '\n'.join(df['quote'].values) model = markovify.NewlineText(text) model.make_short_sentence(140)

Slide 81

Slide 81 text

import markovify import pandas as pd df = pd.read_csv('data/highlights.csv') text = '\n'.join(df['quote'].values) model = markovify.NewlineText(text) model.make_short_sentence(140)

Slide 82

Slide 82 text

model.make_short_sentence(140) Early Dates are Interviews; don't waste the opportunity to actually move toward a romantic relationship.

Slide 83

Slide 83 text

model.make_short_sentence(140) Early Dates are Interviews; don't waste the opportunity to actually move toward a romantic relationship. Pick a charity or two and set up autopay.

Slide 84

Slide 84 text

model.make_short_sentence(140) Early Dates are Interviews; don't waste the opportunity to actually move toward a romantic relationship. Pick a charity or two and set up autopay. Everyone always wants money, which means you can implement any well-defined function simply by connecting with people’s experiences.

Slide 85

Slide 85 text

model.make_short_sentence(140) Early Dates are Interviews; don't waste the opportunity to actually move toward a romantic relationship. Pick a charity or two and set up autopay. Everyone always wants money, which means you can implement any well-defined function simply by connecting with people’s experiences. The more you play, the more varied experiences you have, the more people alive under worse conditions.

Slide 86

Slide 86 text

model.make_short_sentence(140) Early Dates are Interviews; don't waste the opportunity to actually move toward a romantic relationship. Pick a charity or two and set up autopay. Everyone always wants money, which means you can implement any well-defined function simply by connecting with people’s experiences. The more you play, the more varied experiences you have, the more people alive under worse conditions. Everything can be swept away by the bear to avoid losing your peace of mind.

Slide 87

Slide 87 text

model.make_short_sentence(140) Early Dates are Interviews; don't waste the opportunity to actually move toward a romantic relationship. Pick a charity or two and set up autopay. Everyone always wants money, which means you can implement any well-defined function simply by connecting with people’s experiences. The more you play, the more varied experiences you have, the more people alive under worse conditions. Everything can be swept away by the bear to avoid losing your peace of mind. Make a spreadsheet. The cells of the future.

Slide 88

Slide 88 text

model.make_short_sentence(140) Early Dates are Interviews; don't waste the opportunity to actually move toward a romantic relationship. Pick a charity or two and set up autopay. Everyone always wants money, which means you can implement any well-defined function simply by connecting with people’s experiences. The more you play, the more varied experiences you have, the more people alive under worse conditions. Everything can be swept away by the bear to avoid losing your peace of mind. Make a spreadsheet. The cells of the future.

Slide 89

Slide 89 text

No content

Slide 90

Slide 90 text

No content

Slide 91

Slide 91 text

No content

Slide 92

Slide 92 text

No content

Slide 93

Slide 93 text

No content

Slide 94

Slide 94 text

No content

Slide 95

Slide 95 text

No content

Slide 96

Slide 96 text

No content

Slide 97

Slide 97 text

No content

Slide 98

Slide 98 text

import requests from bs4 import BeautifulSoup book = 'Fluke: Or, I Know Why the Winged Whale Sings' payload = {'q': book, 'commit': 'Search'} r = requests.get('https://www.goodreads.com/quotes/search', params=payload) soup = BeautifulSoup(r.text, 'html.parser') for s in soup(['script']): s.decompose() soup.find_all(class_='quoteText')

Slide 99

Slide 99 text

import requests from bs4 import BeautifulSoup book = 'Fluke: Or, I Know Why the Winged Whale Sings' payload = {'q': book, 'commit': 'Search'} r = requests.get('https://www.goodreads.com/quotes/search', params=payload) soup = BeautifulSoup(r.text, 'html.parser') for s in soup(['script']): s.decompose() soup.find_all(class_='quoteText')

Slide 100

Slide 100 text

import requests from bs4 import BeautifulSoup book = 'Fluke: Or, I Know Why the Winged Whale Sings' payload = {'q': book, 'commit': 'Search'} r = requests.get('https://www.goodreads.com/quotes/search', params=payload) soup = BeautifulSoup(r.text, 'html.parser') for s in soup(['script']): s.decompose() soup.find_all(class_='quoteText')

Slide 101

Slide 101 text

s = soup.find_all(class_='quoteText')[5]

Slide 102

Slide 102 text

s = soup.find_all(class_='quoteText')[5]

Slide 103

Slide 103 text

s = soup.find_all(class_='quoteText')[5]

Slide 104

Slide 104 text

def get_quotes(book): payload = {'q': book, 'commit': 'Search'} r = requests.get('https://www.goodreads.com/quotes/search', params=payload) soup = BeautifulSoup(r.text, 'html.parser') # remove script tags for s in soup(['script']): s.decompose() # parse text book = {'quote': [], 'author': [], 'title': []} for s in soup.find_all(class_='quoteText'): s = s.text.replace('\n', '').strip() quote = re.search('(.*)', s, re.IGNORECASE).group(1) meta = re.search('(.*)', s, re.IGNORECASE).group(1) meta = re.sub('[^,.a-zA-Z\s]', '', meta) meta = re.sub('\s+', ' ', meta).strip() meta = re.sub('^\s', '', meta).strip() try: author, title = meta.split(',') except ValueError: author, title = meta, None book['quote'].append(quote) book['author'].append(author) book['title'].append(title) return book

Slide 105

Slide 105 text

def get_quotes(book): payload = {'q': book, 'commit': 'Search'} r = requests.get('https://www.goodreads.com/quotes/search', params=payload) soup = BeautifulSoup(r.text, 'html.parser') # remove script tags for s in soup(['script']): s.decompose() # parse text book = {'quote': [], 'author': [], 'title': []} for s in soup.find_all(class_='quoteText'): s = s.text.replace('\n', '').strip() quote = re.search('(.*)', s, re.IGNORECASE).group(1) meta = re.search('(.*)', s, re.IGNORECASE).group(1) meta = re.sub('[^,.a-zA-Z\s]', '', meta) meta = re.sub('\s+', ' ', meta).strip() meta = re.sub('^\s', '', meta).strip() try: author, title = meta.split(',') except ValueError: author, title = meta, None book['quote'].append(quote) book['author'].append(author) book['title'].append(title) return book

Slide 106

Slide 106 text

def get_quotes(book): payload = {'q': book, 'commit': 'Search'} r = requests.get('https://www.goodreads.com/quotes/search', params=payload) soup = BeautifulSoup(r.text, 'html.parser') # remove script tags for s in soup(['script']): s.decompose() # parse text book = {'quote': [], 'author': [], 'title': []} for s in soup.find_all(class_='quoteText'): s = s.text.replace('\n', '').strip() quote = re.search('(.*)', s, re.IGNORECASE).group(1) meta = re.search('(.*)', s, re.IGNORECASE).group(1) meta = re.sub('[^,.a-zA-Z\s]', '', meta) meta = re.sub('\s+', ' ', meta).strip() meta = re.sub('^\s', '', meta).strip() try: author, title = meta.split(',') except ValueError: author, title = meta, None book['quote'].append(quote) book['author'].append(author) book['title'].append(title) return book

Slide 107

Slide 107 text

books = [ 'Fluke: Or, I Know Why the Winged Whale Sings', 'Shades of Grey Fforde', 'Neverwhere Gaiman', 'The Graveyard Book' ] all_books = {'quote': [], 'author': [], 'title': []} for b in books: print(f"Getting: {b}") b = get_quotes(b) all_books['author'].extend(b['author']) all_books['title'].extend(b['title']) all_books['quote'].extend(b['quote']) audio = pd.DataFrame(all_books) audio.to_csv('audio.csv', index=False, encoding='utf-8-sig')

Slide 108

Slide 108 text

books = [ 'Fluke: Or, I Know Why the Winged Whale Sings', 'Shades of Grey Fforde', 'Neverwhere Gaiman', 'The Graveyard Book' ] all_books = {'quote': [], 'author': [], 'title': []} for b in books: print(f"Getting: {b}") b = get_quotes(b) all_books['author'].extend(b['author']) all_books['title'].extend(b['title']) all_books['quote'].extend(b['quote']) audio = pd.DataFrame(all_books) audio.to_csv('audio.csv', index=False, encoding='utf-8-sig')

Slide 109

Slide 109 text

No content

Slide 110

Slide 110 text

Slide 111

Slide 111 text

Slide 112

Slide 112 text

No content

Slide 113

Slide 113 text

No content

Slide 114

Slide 114 text

No content

Slide 115

Slide 115 text

No content

Slide 116

Slide 116 text

No content

Slide 117

Slide 117 text

No content

Slide 118

Slide 118 text

from traces import TimeSeries as TTS from datetime import datetime d = {} for i, row in df.iterrows(): date = pd.Timestamp(row['datetime']).to_pydatetime() door = row['door'] d[date] = door tts = TTS(d)

Slide 119

Slide 119 text

from traces import TimeSeries as TTS from datetime import datetime d = {} for i, row in df.iterrows(): date = pd.Timestamp(row['datetime']).to_pydatetime() door = row['door'] d[date] = door tts = TTS(d)

Slide 120

Slide 120 text

from traces import TimeSeries as TTS from datetime import datetime d = {} for i, row in df.iterrows(): date = pd.Timestamp(row['datetime']).to_pydatetime() door = row['door'] d[date] = door tts = TTS(d)

Slide 121

Slide 121 text

from traces import TimeSeries as TTS from datetime import datetime d = {} for i, row in df.iterrows(): date = pd.Timestamp(row['datetime']).to_pydatetime() door = row['door'] d[date] = door tts = TTS(d)

Slide 122

Slide 122 text

tts.distribution( start=datetime(2018, 4, 1), end=datetime(2018, 4, 21) )

Slide 123

Slide 123 text

Histogram({0: 0.682, 1: 0.318}) tts.distribution( start=datetime(2018, 4, 1), end=datetime(2018, 4, 21) )

Slide 124

Slide 124 text

No content

Slide 125

Slide 125 text

No content

Slide 126

Slide 126 text

No content

Slide 127

Slide 127 text

No content

Slide 128

Slide 128 text

df = pd.read_csv('data/beer.csv') df['time'] = pd.to_timedelta(df['time'] + ':00')

Slide 129

Slide 129 text

df = pd.melt(df, id_vars=['time', 'beer', 'ml', 'abv'], value_vars=['Mark', 'Max', 'Adam'], var_name='name', value_name='quantity' ) weight = pd.DataFrame({ 'name': ['Max', 'Mark', 'Adam'], 'weight': [165, 155, 200] }) df = pd.merge(df, weight, how='left', on='name')

Slide 130

Slide 130 text

df['standard_drink'] = ( df['ml'] * (df['abv'] / 100) * df['quantity']) / 17.2) # standard drink has 17.2 ml of alcohol df['cumsum_drinks'] = ( df.groupby([‘name’])[‘standard_drink'].apply(lambda x: x.cumsum())) df['hours'] = df['time'] - df[‘time'].min() df['hours'] = df['hours'].apply(lambda x: x.seconds / 3600)

Slide 131

Slide 131 text

df['standard_drink'] = ( df['ml'] * (df['abv'] / 100) * df['quantity']) / 17.2) # standard drink has 17.2 ml of alcohol df['cumsum_drinks'] = ( df.groupby([‘name’])[‘standard_drink'].apply(lambda x: x.cumsum())) df['hours'] = df['time'] - df[‘time'].min() df['hours'] = df['hours'].apply(lambda x: x.seconds / 3600)

Slide 132

Slide 132 text

def ebac(standard_drinks, weight, hours): # https://en.wikipedia.org/wiki/Blood_alcohol_content BLOOD_BODY_WATER_CONSTANT = 0.806 SWEDISH_STANDARD = 1.2 BODY_WATER = 0.58 META_CONSTANT = 0.015 def lb_to_kg(weight): return weight * 0.4535924 n = BLOOD_BODY_WATER_CONSTANT * standard_drinks * SWEDISH_STANDARD d = BODY_WATER * lb_to_kg(weight) bac = (n / d - META_CONSTANT * hours) return bac

Slide 133

Slide 133 text

def ebac(standard_drinks, weight, hours): # https://en.wikipedia.org/wiki/Blood_alcohol_content BLOOD_BODY_WATER_CONSTANT = 0.806 SWEDISH_STANDARD = 1.2 BODY_WATER = 0.58 META_CONSTANT = 0.015 def lb_to_kg(weight): return weight * 0.4535924 n = BLOOD_BODY_WATER_CONSTANT * standard_drinks * SWEDISH_STANDARD d = BODY_WATER * lb_to_kg(weight) bac = (n / d - META_CONSTANT * hours) return bac df['bac'] = df.apply( lambda row: ebac( row['cumsum_drinks'], row['weight'], row['hours'] ), axis=1 )

Slide 134

Slide 134 text

No content

Slide 135

Slide 135 text

No content

Slide 136

Slide 136 text

No content

Slide 137

Slide 137 text

No content

Slide 138

Slide 138 text

No content

Slide 139

Slide 139 text

No content

Slide 140

Slide 140 text

No content

Slide 141

Slide 141 text

No content

Slide 142

Slide 142 text

No content

Slide 143

Slide 143 text

No content

Slide 144

Slide 144 text

No content

Slide 145

Slide 145 text

No content

Slide 146

Slide 146 text

No content

Slide 147

Slide 147 text

No content

Slide 148

Slide 148 text

import mechanicalsoup def fetch_data(): browser = mechanicalsoup.StatefulBrowser( soup_config={'features': 'lxml'}, raise_on_404=True, user_agent='MyBot/0.1: mysite.example.com/bot_info', ) browser.open('https://bikesharetoronto.com/members/login') browser.select_form('form') browser['userName'] = BIKESHARE_USERNAME browser['password'] = BIKESHARE_PASSWORD browser.submit_selected() browser.follow_link('trips') browser.select_form('form') browser['startDate'] = '2017-10-01' browser['endDate'] = '2018-04-01' browser.submit_selected() html = str(browser.get_current_page()) df = pd.read_html(html)[0] return df df = fetch_data()

Slide 149

Slide 149 text

No content

Slide 150

Slide 150 text

import mechanicalsoup def fetch_data(): browser = mechanicalsoup.StatefulBrowser( soup_config={'features': 'lxml'}, raise_on_404=True, user_agent='MyBot/0.1: mysite.example.com/bot_info', ) browser.open('https://bikesharetoronto.com/members/login') browser.select_form('form') browser['userName'] = BIKESHARE_USERNAME browser['password'] = BIKESHARE_PASSWORD browser.submit_selected() browser.follow_link('trips') browser.select_form('form') browser['startDate'] = '2017-10-01' browser['endDate'] = '2018-04-01' browser.submit_selected() html = str(browser.get_current_page()) df = pd.read_html(html)[0] return df df = fetch_data()

Slide 151

Slide 151 text

import mechanicalsoup def fetch_data(): browser = mechanicalsoup.StatefulBrowser( soup_config={'features': 'lxml'}, raise_on_404=True, user_agent='MyBot/0.1: mysite.example.com/bot_info', ) browser.open('https://bikesharetoronto.com/members/login') browser.select_form('form') browser['userName'] = BIKESHARE_USERNAME browser['password'] = BIKESHARE_PASSWORD browser.submit_selected() browser.follow_link('trips') browser.select_form('form') browser['startDate'] = '2017-10-01' browser['endDate'] = '2018-04-01' browser.submit_selected() html = str(browser.get_current_page()) df = pd.read_html(html)[0] return df df = fetch_data()

Slide 152

Slide 152 text

import mechanicalsoup def fetch_data(): browser = mechanicalsoup.StatefulBrowser( soup_config={'features': 'lxml'}, raise_on_404=True, user_agent='MyBot/0.1: mysite.example.com/bot_info', ) browser.open('https://bikesharetoronto.com/members/login') browser.select_form('form') browser['userName'] = BIKESHARE_USERNAME browser['password'] = BIKESHARE_PASSWORD browser.submit_selected() browser.follow_link('trips') browser.select_form('form') browser['startDate'] = '2017-10-01' browser['endDate'] = '2018-04-01' browser.submit_selected() html = str(browser.get_current_page()) df = pd.read_html(html)[0] return df df = fetch_data()

Slide 153

Slide 153 text

import mechanicalsoup def fetch_data(): browser = mechanicalsoup.StatefulBrowser( soup_config={'features': 'lxml'}, raise_on_404=True, user_agent='MyBot/0.1: mysite.example.com/bot_info', ) browser.open('https://bikesharetoronto.com/members/login') browser.select_form('form') browser['userName'] = BIKESHARE_USERNAME browser['password'] = BIKESHARE_PASSWORD browser.submit_selected() browser.follow_link('trips') browser.select_form('form') browser['startDate'] = '2017-10-01' browser['endDate'] = '2018-04-01' browser.submit_selected() html = str(browser.get_current_page()) df = pd.read_html(html)[0] return df df = fetch_data()

Slide 154

Slide 154 text

No content

Slide 155

Slide 155 text

No content

Slide 156

Slide 156 text

No content

Slide 157

Slide 157 text

No content

Slide 158

Slide 158 text

def get_geocode(query): url = 'https://maps.googleapis.com/maps/api/geocode/json?' payload = {'address': query + 'Toronto', 'key': GEOCODING_KEY} r = requests.get(url, params=payload) results = r.json()['results'][0] return { 'query': query, 'place_id': results['place_id'], 'formatted_address': results['formatted_address'], 'lat': results['geometry']['location']['lat'], 'lng': results['geometry']['location']['lng'] }

Slide 159

Slide 159 text

def get_geocode(query): url = 'https://maps.googleapis.com/maps/api/geocode/json?' payload = {'address': query + 'Toronto', 'key': GEOCODING_KEY} r = requests.get(url, params=payload) results = r.json()['results'][0] return { 'query': query, 'place_id': results['place_id'], 'formatted_address': results['formatted_address'], 'lat': results['geometry']['location']['lat'], 'lng': results['geometry']['location']['lng'] }

Slide 160

Slide 160 text

def get_geocode(query): url = 'https://maps.googleapis.com/maps/api/geocode/json?' payload = {'address': query + 'Toronto', 'key': GEOCODING_KEY} r = requests.get(url, params=payload) results = r.json()['results'][0] return { 'query': query, 'place_id': results['place_id'], 'formatted_address': results['formatted_address'], 'lat': results['geometry']['location']['lat'], 'lng': results['geometry']['location']['lng'] }

Slide 161

Slide 161 text

No content

Slide 162

Slide 162 text

No content

Slide 163

Slide 163 text

No content

Slide 164

Slide 164 text

No content

Slide 165

Slide 165 text

No content

Slide 166

Slide 166 text

Slide 167

Slide 167 text

No content

Slide 168

Slide 168 text

No content

Slide 169

Slide 169 text

import pandas as pd import numpy as np import seaborn as sns df = sns.load_dataset('titanic') df = df[['survived', 'pclass', 'sex', 'age', 'fare']].copy() df

Slide 170

Slide 170 text

import pandas as pd import numpy as np import seaborn as sns df = sns.load_dataset('titanic') df = df[['survived', 'pclass', 'sex', 'age', 'fare']].copy() df

Slide 171

Slide 171 text

import pandas as pd import numpy as np import seaborn as sns df = sns.load_dataset('titanic') df = df[['survived', 'pclass', 'sex', 'age', 'fare']].copy() df

Slide 172

Slide 172 text

df.rename( columns={ 'survived': 'mummified', 'pclass': 'class', 'fare': 'debens' }, inplace=True) df['debens'] = round(df['debens'] * 10, -1) # inverse df['mummified'] = np.where(df['mummified'] == 0, 1, 0) df = pd.get_dummies(df) df = df.drop('sex_female', axis=1) df.rename(columns={'sex_male': 'male'}, inplace=True)

Slide 173

Slide 173 text

df.rename( columns={ 'survived': 'mummified', 'pclass': 'class', 'fare': 'debens' }, inplace=True) df['debens'] = round(df['debens'] * 10, -1) # inverse df['mummified'] = np.where(df['mummified'] == 0, 1, 0) df = pd.get_dummies(df) df = df.drop('sex_female', axis=1) df.rename(columns={'sex_male': 'male'}, inplace=True)

Slide 174

Slide 174 text

df.rename( columns={ 'survived': 'mummified', 'pclass': 'class', 'fare': 'debens' }, inplace=True) df['debens'] = round(df['debens'] * 10, -1) # inverse df['mummified'] = np.where(df['mummified'] == 0, 1, 0) df = pd.get_dummies(df) df = df.drop('sex_female', axis=1) df.rename(columns={'sex_male': 'male'}, inplace=True)

Slide 175

Slide 175 text

df.rename( columns={ 'survived': 'mummified', 'pclass': 'class', 'fare': 'debens' }, inplace=True) df['debens'] = round(df['debens'] * 10, -1) # inverse df['mummified'] = np.where(df['mummified'] == 0, 1, 0) df = pd.get_dummies(df) df = df.drop('sex_female', axis=1) df.rename(columns={'sex_male': 'male'}, inplace=True)

Slide 176

Slide 176 text

df.rename( columns={ 'survived': 'mummified', 'pclass': 'class', 'fare': 'debens' }, inplace=True) df['debens'] = round(df['debens'] * 10, -1) # inverse df['mummified'] = np.where(df['mummified'] == 0, 1, 0) df = pd.get_dummies(df) df = df.drop('sex_female', axis=1) df.rename(columns={'sex_male': 'male'}, inplace=True)

Slide 177

Slide 177 text

No content

Slide 178

Slide 178 text

No content

Slide 179

Slide 179 text

No content

Slide 180

Slide 180 text

No content

Slide 181

Slide 181 text

arm leg

Slide 182

Slide 182 text

import seaborn as sns df = sns.load_dataset('iris')

Slide 183

Slide 183 text

No content

Slide 184

Slide 184 text

No content

Slide 185

Slide 185 text

transformers = { 'setosa': 'autobot', 'versicolor': 'decepticon', 'virginica': 'predacon'} df['species'] = df['species'].map(transformers)

Slide 186

Slide 186 text

transformers = { 'setosa': 'autobot', 'versicolor': 'decepticon', 'virginica': 'predacon'} df['species'] = df['species'].map(transformers)

Slide 187

Slide 187 text

df.rename( columns={ 'sepal_length': 'leg_length', 'sepal_width': 'leg_width', 'petal_length': 'arm_length', 'petal_width': 'arm_width' }, inplace=True )

Slide 188

Slide 188 text

(alt.Chart(df) .mark_circle().encode( x=alt.X(alt.repeat('column'), type='quantitative'), y=alt.Y(alt.repeat('row'), type='quantitative'), color='species:N') .properties( width=90, height=90) .repeat( background='white', row=['leg_length', 'leg_width', 'arm_length', 'arm_width'], column=['leg_length', 'leg_width', 'arm_length', 'arm_width']) .interactive() )

Slide 189

Slide 189 text

(alt.Chart(df) .mark_circle().encode( x=alt.X(alt.repeat('column'), type='quantitative'), y=alt.Y(alt.repeat('row'), type='quantitative'), color='species:N') .properties( width=90, height=90) .repeat( background='white', row=['leg_length', 'leg_width', 'arm_length', 'arm_width'], column=['leg_length', 'leg_width', 'arm_length', 'arm_width']) .interactive() )

Slide 190

Slide 190 text

No content

Slide 191

Slide 191 text

No content

Slide 192

Slide 192 text

No content

Slide 193

Slide 193 text

No content

Slide 194

Slide 194 text

pip install mummify "You suck at Git. And logging. But it's not your fault."

Slide 195

Slide 195 text

No content