Module 9 · Data capstone: 911 calls · Lesson 43 of 66

Find the patterns

When do calls come in? Count by weekday, month, date and hour, and draw heat maps.

In this lesson · about 30 minutes

  • Compare groups with count plots split by hue
  • Count by month and by date with groupby, and chart the trend
  • Reshape counts with unstack and draw them as a heat map

Every question here starts from the data with the columns you made: Reason, Hour, Month and Day of Week.

Exercise

8. Calls by weekday and reason

Draw a count plot of Day of Week, split by Reason with hue.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv('911.csv')
df['Reason'] = df['title'].apply(lambda title: title.split(':')[0])
df['timeStamp'] = pd.to_datetime(df['timeStamp'])
df['Hour'] = df['timeStamp'].dt.hour
df['Month'] = df['timeStamp'].dt.month
dmap = {0: 'Mon', 1: 'Tue', 2: 'Wed', 3: 'Thu', 4: 'Fri', 5: 'Sat', 6: 'Sun'}
df['Day of Week'] = df['timeStamp'].dt.dayofweek.map(dmap)

Exercise

9. Calls by month and reason

Do the same with Month on the x axis. Some months are missing from the data. Notice which.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv('911.csv')
df['Reason'] = df['title'].apply(lambda title: title.split(':')[0])
df['timeStamp'] = pd.to_datetime(df['timeStamp'])
df['Hour'] = df['timeStamp'].dt.hour
df['Month'] = df['timeStamp'].dt.month
dmap = {0: 'Mon', 1: 'Tue', 2: 'Wed', 3: 'Thu', 4: 'Fri', 5: 'Sat', 6: 'Sun'}
df['Day of Week'] = df['timeStamp'].dt.dayofweek.map(dmap)

Filling the gap with groupby

To see the trend across all months, count the calls per month with groupby. df.groupby('Month').count() counts the non-empty values of every column for each month. Columns with gaps, such as twp or zip, count a little lower, so read the count from e, which is never empty.

Exercise

10. Monthly totals

Make byMonth = df.groupby('Month').count(), then plot the e column of it as a line.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv('911.csv')
df['Reason'] = df['title'].apply(lambda title: title.split(':')[0])
df['timeStamp'] = pd.to_datetime(df['timeStamp'])
df['Hour'] = df['timeStamp'].dt.hour
df['Month'] = df['timeStamp'].dt.month
dmap = {0: 'Mon', 1: 'Tue', 2: 'Wed', 3: 'Thu', 4: 'Fri', 5: 'Sat', 6: 'Sun'}
df['Day of Week'] = df['timeStamp'].dt.dayofweek.map(dmap)

A trend line through the months

Exercise

11. Calls per day

Make a Date column from timeStamp with .dt.date. Then count calls per date with groupby and plot the e column as a line.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv('911.csv')
df['Reason'] = df['title'].apply(lambda title: title.split(':')[0])
df['timeStamp'] = pd.to_datetime(df['timeStamp'])
df['Hour'] = df['timeStamp'].dt.hour
df['Month'] = df['timeStamp'].dt.month
dmap = {0: 'Mon', 1: 'Tue', 2: 'Wed', 3: 'Thu', 4: 'Fri', 5: 'Sat', 6: 'Sun'}
df['Day of Week'] = df['timeStamp'].dt.dayofweek.map(dmap)

One chart per reason

Filter the rows first, then count by date. Here are the traffic calls; change 'Traffic' to 'Fire' or 'EMS' and run again.

Heat maps by hour and weekday

Group by two columns at once to count calls for every weekday and hour: df.groupby(by=['Day of Week', 'Hour']).count()['Reason']. That gives one long column with a two-level index. .unstack() moves the inner level (hours) into columns, giving a 7 by 24 table: just the shape a heat map needs.

Exercise

12. Weekday by hour

Build dayHour: the number of calls for each Day of Week (rows) and Hour (columns). Then draw it as a heat map with the 'viridis' color map.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv('911.csv')
df['Reason'] = df['title'].apply(lambda title: title.split(':')[0])
df['timeStamp'] = pd.to_datetime(df['timeStamp'])
df['Hour'] = df['timeStamp'].dt.hour
df['Month'] = df['timeStamp'].dt.month
dmap = {0: 'Mon', 1: 'Tue', 2: 'Wed', 3: 'Thu', 4: 'Fri', 5: 'Sat', 6: 'Sun'}
df['Day of Week'] = df['timeStamp'].dt.dayofweek.map(dmap)

Group similar days together

A cluster map reorders the rows and columns so that similar ones sit together. The weekend days pair up, and so do the workday rush hours.

Exercise

13. Weekday by month

Now make dayMonth, with months as the columns instead of hours, and draw it as a heat map with the 'coolwarm' color map.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv('911.csv')
df['Reason'] = df['title'].apply(lambda title: title.split(':')[0])
df['timeStamp'] = pd.to_datetime(df['timeStamp'])
df['Hour'] = df['timeStamp'].dt.hour
df['Month'] = df['timeStamp'].dt.month
dmap = {0: 'Mon', 1: 'Tue', 2: 'Wed', 3: 'Thu', 4: 'Fri', 5: 'Sat', 6: 'Sun'}
df['Day of Week'] = df['timeStamp'].dt.dayofweek.map(dmap)

Exercises solved: 0 of 6

Tip: solve each exercise first. Press Check to test your code.

Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.