forked from roshan-d21/Chicago-Crime-Analysis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PartI.py
153 lines (127 loc) · 5.41 KB
/
PartI.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
# -*- coding: utf-8 -*-
"""Crime_Analysis.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1g9UImZSAiMZLo4h3PifflD86Gmv8Nfpq
"""
# Commented out IPython magic to ensure Python compatibility.
#import modules
import numpy as np
import pandas as pd
from pandas import *
import os
import csv
import matplotlib.pyplot as plt
import seaborn as sns
# %matplotlib inline
import datetime
from scipy import stats
sns.set_style("darkgrid")
import matplotlib.image as mpimg
from IPython.display import IFrame
import folium
from folium import plugins
from folium.plugins import MarkerCluster, FastMarkerCluster, HeatMapWithTime
from google.colab import drive
drive.mount('/content/drive')
crime = read_csv('/content/drive/MyDrive/Crimes_-_2001_to_Present.csv', iterator=True, chunksize=100000)
crime_data = concat(crime, ignore_index=True)
# print data's shape
crime_data.shape
crime_data.info()
plt.figure(figsize=(10,7))
sns.heatmap(crime_data.isnull(), cbar = False)
# convert dates to pandas datetime format
crime_data.Date = pd.to_datetime(crime_data.Date, format='%m/%d/%Y %I:%M:%S %p')
crime_data.index = pd.DatetimeIndex(crime_data.Date)
print(crime_data.index)
plt.figure(figsize = (15, 10))
sns.countplot(y= 'Location Description', data = crime_data, order = crime_data['Location Description'].value_counts().iloc[:10].index)
plt.figure(figsize = (15, 10))
sns.countplot(y= 'Primary Type', data = crime_data, order = crime_data['Primary Type'].value_counts().iloc[:10].index)
crime_data.groupby([crime_data.index.month]).size().plot(kind='barh')
plt.ylabel('Months of the year')
plt.xlabel('Number of crimes')
plt.title('Number of crimes by month of the year')
plt.show()
days = ['Monday','Tuesday','Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
crime_data.groupby([crime_data.index.dayofweek]).size().plot(kind='barh')
plt.ylabel('Days of the week')
plt.yticks(np.arange(7), days)
plt.xlabel('Number of crimes')
plt.title('Number of crimes by day of the week')
plt.show()
crime_data_count_date = crime_data.pivot_table('ID', aggfunc=np.size, columns='Primary Type', index=crime_data.index.date, fill_value=0)
crime_data_count_date.index = pd.DatetimeIndex(crime_data_count_date.index)
plo = crime_data_count_date.rolling(365).sum().plot(figsize=(12, 30), subplots=True, layout=(-1, 3), sharex=False, sharey=False)
crime_data = crime_data.loc[(crime_data['X Coordinate']!=0)]
sns.lmplot('X Coordinate',
'Y Coordinate',
data=crime_data[:],
fit_reg=False,
hue="District",
palette='Dark2',
size=12,
ci=2,
scatter_kws={"marker": "D",
"s": 10})
ax = plt.gca()
ax.set_title("All Crime Distribution per District")
col2 = ['Date','Primary Type','Arrest','Domestic','District','X Coordinate','Y Coordinate']
multiple_crimes = crime_data[col2]
multiple_crimes = multiple_crimes[multiple_crimes['Primary Type']\
.isin(['HOMICIDE','BURGLARY','NARCOTICS','WEAPONS VIOLATION'])]
# clean some rouge (0,0) coordinates
multiple_crimes = multiple_crimes[multiple_crimes['X Coordinate']!=0]
multiple_crimes.head()
g = sns.lmplot(x="X Coordinate",
y="Y Coordinate",
col="Primary Type",
data=multiple_crimes.dropna(),
col_wrap=2, size=6, fit_reg=False,
sharey=False,
scatter_kws={"marker": "D",
"s": 10})
df_public_peace = crime_data[crime_data['Primary Type'] == 'PUBLIC PEACE VIOLATION']
df_public_data = pd.DataFrame({"Counts": df_public_peace['Description'].value_counts(), "Description" : df_public_peace['Description'].value_counts().index})
df_public_data.reset_index(inplace=True)
df_public_data = df_public_data.drop(columns=['index'], axis = 1)
df_public_data.head()
plt.figure(figsize = (15, 7))
sns.barplot(y ="Description", x = "Counts", data = df_public_data, palette="cool")
# Take only Burglary
burglary_data = crime_data[crime_data['Primary Type']=='BURGLARY']
burglary_data.head()
burglary_data = burglary_data.dropna()
burglary_data = burglary_data.loc[(burglary_data['X Coordinate']!=0)]
sns.lmplot('X Coordinate',
'Y Coordinate',
data=burglary_data[:],
fit_reg=False,
hue="District",
palette='Dark2',
size=12,
ci=2,
scatter_kws={"marker": "D",
"s": 10})
ax = plt.gca()
ax.set_title("All Homicides (2001-2020) per District")
plt.figure(figsize=(12,6))
sns.barplot(x='Year',
y='BURGLARY',
data=burglary_data.groupby(['Year'])['Primary Type'].value_counts().\
unstack().reset_index(),
color='steelblue').set_title("CHICAGO BURGLARY RATES: 2001 - 2020")
# create new columns from date column -- Year, Month, Day, Hour, Minutes, DayOfWeek
burglary_data['Year'] = burglary_data['Date'].dt.year
burglary_data['Month'] = burglary_data['Date'].dt.month
burglary_data['Day'] = burglary_data['Date'].dt.day
burglary_data['Weekday'] = burglary_data['Date'].dt.dayofweek
burglary_data['HourOfDay'] = burglary_data['Date'].dt.hour
burglary_data = burglary_data.sort_values('Year')
print(burglary_data)
con = burglary_data.to_csv('output.csv')
from google.colab import files
files.download('output.csv')
# PART I ENDS HERE WITH THE BURGLARY DATA SAVED IN output.csv
# Move on to PART II which uses R to do the forecasting