-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdataset_analysis.py
268 lines (194 loc) · 8.59 KB
/
dataset_analysis.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# -*- coding: utf-8 -*-
"""dataset_analysis.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1m-ejrZtyEEpmTm6FxD9_paparJ60Cunc
#Import NumPy, Pandas, Seaborn, Matplotlib
"""
# Commented out IPython magic to ensure Python compatibility.
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# %matplotlib inline
"""#Chicago Crime Dataset Download & Feature Dropping
##Download and extract the Chicago Crime dataset
"""
from google.colab import drive
drive.mount('/content/drive')
crimes1 = pd.read_csv('drive/My Drive/Colab Notebooks/Chicago_Crimes_2001_to_2004.csv', error_bad_lines=False)
crimes2 = pd.read_csv('drive/My Drive/Colab Notebooks/Chicago_Crimes_2005_to_2007.csv', error_bad_lines=False)
crimes3 = pd.read_csv('drive/My Drive/Colab Notebooks/Chicago_Crimes_2008_to_2011.csv', error_bad_lines=False)
crimes4 = pd.read_csv('drive/My Drive/Colab Notebooks/Chicago_Crimes_2012_to_2017.csv', error_bad_lines=False)
crimes = pd.concat([crimes1, crimes2, crimes3, crimes4])
del crimes1
del crimes2
del crimes3
del crimes4
"""##Display the first contents of the data"""
crimes.head(10)
"""##Print the shape of the data with and without duplicates"""
print('Before Dropping Duplicates: ' + str(crimes.shape))
crimes.drop_duplicates(subset=['ID', 'Case Number'], inplace=True)
print('After Dropping Duplicates: ' + str(crimes.shape))
"""##Drop the features that won't be used"""
crimes.drop(columns=['Unnamed: 0', 'ID', 'Case Number', 'IUCR', 'Location',
'FBI Code', 'X Coordinate', 'Y Coordinate', 'Year',
'Updated On'], inplace=True, axis=1)
"""##Display the data after dropping the unused features"""
crimes.head(10)
"""##Displays the columns that have null data"""
crimes.isnull().sum(axis=0)
"""##Convert date to match format for Pandas"""
crimes['Date'] = pd.to_datetime(crimes['Date'], format='%m/%d/%Y %I:%M:%S %p')
crimes.index = pd.DatetimeIndex(crimes['Date'])
"""#Analyze time
##Display the number of crimes per month for all years
"""
plt.figure(figsize=(12, 8))
crimes.resample('M').size().plot()
plt.xlabel('Year')
plt.ylabel('Number of Crimes')
plt.show()
"""##Display the heatmap of crimes per month for all years"""
heatmap_month = pd.DataFrame(crimes.resample('M').size(), columns=['Crimes'])
heatmap_month['Year'] = heatmap_month.index.year.astype(str)
heatmap_month['Month'] = heatmap_month.index.month.astype(str)
plt.figure(figsize=(24,8))
sns.heatmap(heatmap_month.pivot('Month', 'Year', 'Crimes').fillna(0).astype(int),
annot=True, fmt='d', linewidths=0.1, cmap='Reds')
"""##Display the number of crimes per year"""
plt.figure(figsize=(12, 8))
crimes.groupby([crimes.index.year]).size().plot(kind='bar')
plt.xlabel('Year')
plt.ylabel('Number of Crimes')
plt.show()
"""##Display the number of crimes per month"""
plt.figure(figsize=(12, 8))
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December']
crimes.groupby([crimes.index.month]).size().plot(kind='bar')
plt.xlabel('Month')
plt.ylabel('Number of Crimes')
plt.xticks(np.arange(12), months)
plt.show()
"""##Display the number of crimes per week"""
plt.figure(figsize=(12, 8))
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday', 'Sunday']
crimes.groupby([crimes.index.dayofweek]).size().plot(kind='bar')
plt.xlabel('Day')
plt.ylabel('Number of Crimes')
plt.xticks(np.arange(7), days)
plt.show()
"""##Display the number of crimes per hour"""
plt.figure(figsize=(16, 8))
crimes.groupby([crimes.index.hour]).size().plot(kind='bar')
plt.xlabel('Hour')
plt.ylabel('Number of Crimes')
plt.show()
"""##Display the heatmap of crimes per hour for all week days"""
heatmap_week = crimes.pivot_table(values='Date', index=crimes.index.weekday,
columns=crimes.index.hour,
aggfunc=np.size).fillna(0).astype(int)
week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday', 'Sunday']
plt.figure(figsize=(32,4))
ax = sns.heatmap(heatmap_week, annot=True, fmt='d', linewidths=0.1,
cmap='Reds', yticklabels=week)
ax.set_xlabel('Hour')
ax.set_ylabel('Week Day')
"""##Display the heatmap of crimes per hour for all types"""
heatmap_type_hour = crimes.pivot_table(values='Date', index='Primary Type',
columns=crimes.index.hour,
aggfunc=np.size).fillna(0).astype(int)
plt.figure(figsize=(32,16))
ax = sns.heatmap(heatmap_type_hour, annot=True, fmt='d',
linewidths=0.1, cmap='Reds')
ax.set_xlabel('Hour')
"""##Display the heatmap of crimes per week day for all types"""
heatmap_type_day = crimes.pivot_table(values='Date', index='Primary Type',
columns=crimes.index.weekday,
aggfunc=np.size).fillna(0).astype(int)
plt.figure(figsize=(24,16))
ax = sns.heatmap(heatmap_type_day, annot=True, fmt='d', linewidths=0.1,
cmap='Reds', xticklabels=week)
ax.set_xlabel('Week Day')
"""#Analyze crimes
##Display the number of crimes per location
"""
plt.figure(figsize=(8, 16))
crimes.groupby([crimes['Location Description']]).size().sort_values(ascending=False)[:40].plot(kind='barh')
plt.xlabel('Number of Crimes')
plt.ylabel('Location')
plt.show()
"""##Display number of crimes per type"""
plt.figure(figsize=(8, 12))
crimes.groupby([crimes['Primary Type']]).size().sort_values(ascending=False)[:25].plot(kind='barh')
plt.xlabel('Number of Crimes')
plt.ylabel('Type')
plt.show()
"""##Display the number of narcotic crime types committed"""
narcotics = crimes[crimes['Primary Type'] == 'NARCOTICS']
plt.figure(figsize=(8, 12))
narcotics.groupby([narcotics['Description']]).size().sort_values(ascending=False)[:25].plot(kind='barh')
plt.xlabel('Number of Crimes')
plt.ylabel('Description')
plt.show()
"""##Display a barplot of arrests for narcotic crimes """
arrest_pos = narcotics[narcotics['Arrest'] == True].shape[0]
arrest_neg = narcotics[narcotics['Arrest'] == False].shape[0]
fig = plt.figure(figsize=(4,4))
ax = fig.add_axes([0,0,1,1])
ax.set_title('Arrests for Narcotic Crimes')
ax.set_xlabel('Arrests')
ax.set_ylabel('Narcotic Crimes')
ax.bar(['True', 'False'], [arrest_pos, arrest_neg])
"""##Display the number of battery crime types committed"""
battery = crimes[crimes['Primary Type'] == 'BATTERY']
plt.figure(figsize=(8, 8))
battery.groupby([battery['Description']]).size().sort_values(ascending=False)[:15].plot(kind='barh')
plt.xlabel('Number of Crimes')
plt.ylabel('Description')
plt.show()
"""##Display a barplot of domestic battery crimes """
battery_pos = battery[battery['Domestic'] == True].shape[0]
battery_neg = battery[battery['Domestic'] == False].shape[0]
fig = plt.figure(figsize=(4,4))
ax = fig.add_axes([0,0,1,1])
ax.set_title('Domestic Battery Crimes')
ax.set_xlabel('Domestic')
ax.set_ylabel('Battery Crimes')
ax.bar(['True', 'False'], [battery_pos, battery_neg])
"""##Display the number of assault crime types committed"""
assault = crimes[crimes['Primary Type'] == 'ASSAULT']
plt.figure(figsize=(8, 8))
assault.groupby([assault['Description']]).size().sort_values(ascending=False)[:10].plot(kind='barh')
plt.xlabel('Number of Crimes')
plt.ylabel('Description')
plt.show()
"""##Display a barplot of domestic assault crimes """
assault_pos = assault[assault['Domestic'] == True].shape[0]
assault_neg = assault[assault['Domestic'] == False].shape[0]
fig = plt.figure(figsize=(4,4))
ax = fig.add_axes([0,0,1,1])
ax.set_title('Domestic Assault Crimes')
ax.set_xlabel('Domestic')
ax.set_ylabel('Assault Crimes')
ax.bar(['True', 'False'], [assault_pos, assault_neg])
"""##Display heatmap of the number of crime types where arrests are successful or not"""
heatmap_arrest = crimes.pivot_table(values='Date', index='Primary Type',
columns='Arrest',
aggfunc=np.size).fillna(0).astype(int).T
plt.figure(figsize=(40,2))
ax = sns.heatmap(heatmap_arrest, annot=True, fmt='d',
linewidths=0.1, cmap='Reds')
ax.set_ylabel('Arrest')
"""##Display heatmap of the number of crime types that are domestic or not"""
heatmap_domestic = crimes.pivot_table(values='Date', index='Primary Type',
columns='Domestic',
aggfunc=np.size).fillna(0).astype(int).T
plt.figure(figsize=(40,2))
ax = sns.heatmap(heatmap_domestic, annot=True, fmt='d',
linewidths=0.1, cmap='Reds')
ax.set_ylabel('Domestic')