-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGitHubProjectSpeedCameraViolations.py
1267 lines (577 loc) · 22.2 KB
/
GitHubProjectSpeedCameraViolations.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding: utf-8
# # IMPORTING NECESSARY LIBRARIES
import pandas as pd
import matplotlib.pyplot as plt
from datetime import date, datetime, time
import datetime as datetime
from statistics import mean, mode, stdev, variance
import numpy as np
import seaborn as sns
import re # might need
import plotly.graph_objects as go
import plotly.express as px
# --------------
# # IMPORTING DATA AND CREATING DATAFRAME
df = pd.read_csv('Speed_Camera_Violations.csv')
df.head()
# ----
# # DATA CLEANING
#
# RENAMING SOME COLUMNS THAT CONTAIN SPACES
# In[6]:
df = df.rename(columns={'CAMERA ID':'CAMERA_ID', 'VIOLATION DATE': 'V_DATE'})
df.head()
# ---
# # REMOVING UNNECESSARY COLUMNS
#
# We will use `.pop()` function to remove unnecessary columns
#
# In[8]:
df.pop('X COORDINATE')
df.pop('Y COORDINATE')
df.pop('LATITUDE')
df.pop('LONGITUDE')
df.pop('LOCATION')
# In[10]:
df.shape # 170521 rows and 4 columns are in `df`
# In[12]:
df.dtypes
# It looks like `ADDRESS`, `CAMERA_ID`, and `V_DATE` columns have mixed numeric and non-numeric values since their datatype is `object`.
# In[13]:
df.info()
# * Looking at the `Non-Null Count` column above, we can see that there are no null values to account for in the 4 columns of `df`.
# * Note: We could have also used `df[df.CAMERA_ID.isnull()]` to see if any rows of, for example, `CAMERA_ID` contained a null value.
# In[14]:
df.describe() # shows description of columns with only numeric data (in this case, only VIOLATIONS)
# Let's find out how many times a certain number of violations occurred
#
# >example: how many instances occurred where there was only 1 violation on any given day?
#
# First, let's list the frequencies of all numbers of daily violations and analyze what we see.
# In[15]:
v_counts = pd.DataFrame(df.groupby(df['VIOLATIONS']).size())
v_counts.head()
# Let's also rename column `0` to `FREQUENCY`
# In[16]:
v_counts.rename(columns={0:'FREQUENCY'}).head()
# In[18]:
v_counts.rename(columns={0:'FREQUENCY'}).tail()
# ### **Interpretations:**
#
# - There were 8715 instances when a camera caught just 1 violation in a day.
# - There were 2 instances when a camera caught **479** violations in a day!
#
#
# #### Let's further analyze those 2 instances.
#
#
# In[19]:
df[df.VIOLATIONS == 479]
# - **We found the corresponding camera. Its ID is CHI149. Both instances were during the Summer of 2015 at 4909 N Cicero Ave.**
#
# 1. One possible conclusion is that this neighborhood is definitely unsafe for children since there were abnormally high number of violations in just 1 day.
# - One might assume that drivers tend to drive poorly in this area, and that is a serious concern.
# - It is possible that there is a sudden bump on the road that causes drivers to drive poorly, making them take unsafe turns or stops.
# - Another possible reason is that there might be frequent spills of oil or other liquids on the road due to some activity either from a home on the street or a nearby factory. This could be causing drivers to lose control over their steering and thus, drive poorly.
# - The traffic lights may not be working well. It might be the case that the lights are not bright enough for those with poorer vision and drivers might have a hard time telling the difference between green, yellow, and red.
# - There are many possible reasons for the high number of violations here. It is important to look into the road construction, traffic lights, and surrounding activities to determine what is correlated with the high number of violations.
#
# **However, it is also important to note that these 2 instances are from only 2 days out of all dates including in the dataset.** Therefore, it is better to plot the number of violations caught by each camera, and identify the potential outliers, and decide whether to keep them in our analysis or discard them. Outliers can serve or disrupt our analysis. It is essential to make good decisions about outliers to avoid false conclusions.
#
# > Sidenote: Another way to filter the rows with the maximum number of accidents is to use the following code: `df[df.VIOLATIONS == max(df.VIOLATIONS)]`
# ---
# ---
# ### OVERALL AVERAGE VIOLATIONS OF EACH CAMERA
# In[20]:
v_avg_per_day = df.groupby(['CAMERA_ID', 'ADDRESS']).mean().sort_values(by='VIOLATIONS', ascending=False)
v_avg_per_day.head()
# `VIOLATIONS` does not state whether the frequency is "per day" or "per month" or "per year". Let's rename the column to make it clear.
# In[21]:
v_avg_per_day.rename(columns={'VIOLATIONS':'AVERAGE VIOLATIONS RECORDED PER DAY'})
# - The resulting table suggests that CHI149 caught more violations per day than other cameras had.
# - However, this could have also been the case due to the abnormally high number of violations on 2 days which increased the camera's overall average number of violations caught.
#
# ---
# <br>
#
# Let's find the total number of violations caught by each camera
# In[22]:
df.groupby('CAMERA_ID').size() # series
# The above result shows the counts of rows pertaining to each camera ID. For example, there are 1584 rows for CHI003.
#
# However, what we need is the number of total `VIOLATIONS` corresponding to each camera.
#
#
# In[53]:
sum_v = df.groupby('CAMERA_ID')[['VIOLATIONS']].sum().sort_values('VIOLATIONS')
# In[64]:
sum_v
# In[69]:
sum_v.reset_index(inplace=True)
# In[174]:
plt.figure(figsize = (50,30))
plt.xticks(rotation = 90, size = 15)
plt.yticks(size = 30)
plt.plot(sum_v.CAMERA_ID,
sum_v.VIOLATIONS,
marker='o',
markersize=6,
linewidth=2)
plt.xlabel(xlabel = "Camera ID",
color = "blue",
size = 50)
plt.ylabel(ylabel = "Total Violations",
color = "blue",
size = 50)
# <br> I will split the data into two halves and visualize each half separately to understand the data points better.
#
# <br>
# In[152]:
plt.figure(figsize = (50,30))
plt.xticks(rotation = 90, size = 30)
plt.yticks(size = 30)
plt.plot(sum_v.CAMERA_ID.iloc[:int(len(sum_v)/2)],
sum_v.VIOLATIONS.iloc[:int(len(sum_v)/2)],
marker='o',
markersize=6,
linewidth=2)
plt.xlabel(xlabel = "Camera ID",
color = "blue",
size = 50)
plt.ylabel(ylabel = "Total Violations",
color = "blue",
size = 50)
# In[169]:
plt.figure(figsize = (50,30))
plt.xticks(rotation = 90, size = 30)
plt.yticks(size = 30)
plt.plot(sum_v.CAMERA_ID.iloc[int(len(sum_v)/2): int(len(sum_v))],
sum_v.VIOLATIONS.iloc[int(len(sum_v)/2): int(len(sum_v))],
marker='o',
markersize=6,
linewidth=2)
plt.xlabel(xlabel = "Camera ID",
color = "blue",
size = 50)
plt.ylabel(ylabel = "Total Violations",
color = "blue",
size = 50)
plt.ylim(0, 300000, 5000)
# ---
# #### notes:
# > sum(df.groupby('CAMERA_ID')[['VIOLATIONS']].sum().sort_values('VIOLATIONS')['VIOLATIONS']) # verifies total of 4924723
#
#
# (81) 0 - 81 | (81) 81 - 161
#
# 0 - len(sum_v.CAMERA_ID/2) | len(sum_v.CAMERA_ID/2) - len(sum_v.CAMERA_ID)-1
#
# - df.groupby('CAMERA_ID').size().count() # quicker way to find number of cameras
# - df.groupby(['CAMERA_ID', 'ADDRESS']).size()
# - str(df.groupby(['CAMERA_ID', 'ADDRESS']).size().count()) + ' unique addresses' # to output result with details
# ---
# ----
#
# **If we want to further analyze the number of days that any camera had caught any number of violations, we can run by the following code (this will display only the first 20 rows):**
#
# <br>
# In[186]:
df.head()
# In[203]:
# pd.DataFrame(df.groupby(['VIOLATIONS', 'CAMERA_ID']).size()).rename(columns={0:'COUNT_OF_DAYS'}).sort_index(ascending=True)[:20]
# In[208]:
df2 = pd.DataFrame(df.groupby(['VIOLATIONS', 'CAMERA_ID']).size()).rename(columns={0:'COUNT_OF_DAYS'}).sort_index(ascending=True).sort_values(['VIOLATIONS', 'COUNT_OF_DAYS', 'CAMERA_ID'])
# In[211]:
df2.reset_index(inplace=True)
# In[223]:
sns.scatterplot(y="VIOLATIONS", x="CAMERA_ID", hue="CAMERA_ID", size="COUNT_OF_DAYS", data=df2[100:110])
# **INTERPRETATION:** Looking at the first row of the dataframe above, we can see that there were 15 days on which the camera CHI005 caught just 1 violation.
#
# <br>
#
# Let's order the rows in descending order of the `VIOLATIONS`.
# In[17]:
numberOfDaysOfViolations = pd.DataFrame(df.groupby(['VIOLATIONS', 'CAMERA_ID']).size().sort_index(ascending=False))[0:147].rename(columns={0:'Count of Days on which `CAMERA_ID` caught `VIOLATIONS` number of violations'})
numberOfDaysOfViolations.head()
# We can see that camera CHI149 caught 479 violations on 2 days.
# ---
#
# <br><br>
# Let's further analyze the violations caught by camera CHI149.
# In[17]:
df[df['CAMERA_ID']=='CHI149']
# In[187]:
df[df['CAMERA_ID']=='CHI149']['VIOLATIONS'].sum()
# Total number of violations caught by CHI149 = 296,755
# In[188]:
df[['CAMERA_ID','VIOLATIONS']]['VIOLATIONS'].sum()
# Total number of violations caught by all cameras = 4,924,723
# ### Interpretation:
#
# - Camera CHI149 caught 296,755 violations out of all the 4,924,723 violations in total over the years.
# - CHI149 caught (296755/4924723*100)% of all violations = 6.026% of all violations.
#
# Even though CHI149 caught so many violations in 2 days, it only recorded 6.026% of all the violations.
#
# Let's analyze what other cameras caught large number of violations to better understand what is going on.
# ---
# ---
# But first, let's analyze CHI149 violation patterns over time
# In[189]:
chi149 = df[df['CAMERA_ID']=='CHI149'].sort_values('V_DATE')
# In[190]:
chi149.head()
# In[191]:
chi149.count() # chi149 contains 1506 rows
# In[192]:
chi149Dates = chi149[['V_DATE', 'VIOLATIONS']]
chi149Dates.sort_values(by=['V_DATE'])
# - The dates are not in order.
# - We will fix this error by splitting the dates in the original dataframe, `df`, into month, day, and year, and then order the dates based on year, and then month, and finally, day.
# In[193]:
# Already imported datetime as datetime
# to extract months, dates, and years of dates
# in order to find the earliest & latest date available.
# creating new columns
df['month'] = pd.DatetimeIndex(df['V_DATE']).month
df['date'] = pd.DatetimeIndex(df['V_DATE']).day
df['year'] = pd.DatetimeIndex(df['V_DATE']).year
sortedDates = df.sort_values(['year', 'month', 'date'])
sortedDates
# **Important Note:** We could have used `df.sort_values('V_DATE')` but it gives the wrong order of dates. The corresponding output will say 01/01/2015 is the earliest (it is the first row of the output),
# and 12/31/2017 is the latest. The reason is that the automatic sorting order is month, date, and then year. However, we need the dates ordered by year, month, and finally, date.
#
# We can do so using the following code:
#
# > `df.sort_values(['year', 'month', 'date'])`
#
# as we did above.
#
# After ordering the dates correctly, we can see that the earliest date of the whole dataset is 07/01/2014 and the latest is 12/23/2018.
#
# <br>
#
#
# <br>
# Let's consider only the rows related to CHI149 again.
# In[194]:
chi149 = sortedDates[sortedDates['CAMERA_ID']=='CHI149'] # since already sorted, do not require `.sort_values(by=['year', 'month', 'date'])`
chi149
# #### We can see that 11/01/2014 is the earliest and 12/23/2018 is the latest recorded date for CHI149.
#
# <br><br>
#
# Now that we have ordered all the rows of chi149, let's plot the dates and number of violations. There are a total of 1506 rows, so the resulting plot will be messy since each date appears only once in this subset of data, and there are many dates to be displayed on the x-axis. So, the x-axis is very hard to read.
# In[60]:
plt.plot_date(chi149.V_DATE, chi149.VIOLATIONS)
# Let's change the plot size and maybe even create subplots for each year.
# In[63]:
plt.figure(figsize=(20,20))
plt.plot_date(chi149.V_DATE, chi149.VIOLATIONS)
# ---
# To make the plot look neater, let's use seaborn (aliased as `sns`)
# In[156]:
sns.set(rc={'figure.figsize':(60,30)})
sns.swarmplot(data=chi149,
x="year",
y="month",
hue="VIOLATIONS",
size=10,
palette="rainbow")
# - In 2015, there are many dates where the total number of violations is very high (red dots).
# - Hence, in the year 2015, CHI149 caught the most number of violations per year.
#
# In[195]:
sns.set(rc={'figure.figsize':(30,60)})
sns.swarmplot(data=df[300:1000],
x="year",
y="month",
hue="VIOLATIONS",
size=10,
alpha=0.5,
palette="rainbow")
# In[ ]:
df.head()
# In[ ]:
fig = px.scatter(chi149,
x="year",
y="month",
color="VIOLATIONS",
color_continuous_scale='Inferno',
hover_name="VIOLATIONS",
size=chi149.VIOLATIONS//10,
animation_frame='V_DATE')
fig.show()
# ----
# In[277]:
a = chi149.sort_values('VIOLATIONS').groupby(chi149.VIOLATIONS).size()
a
# In[295]:
b = chi149.sort_values('V_DATE').groupby(['year','month','date']).size()
b = pd.DataFrame(b)
b.index
# In[306]:
df.sort_values(['year', 'month', 'date', 'VIOLATIONS', 'CAMERA_ID', 'ADDRESS'])
# In[307]:
ymdVCA = df.sort_values(['year', 'month', 'date', 'VIOLATIONS', 'CAMERA_ID', 'ADDRESS'])
# In[308]:
type(ymdVCA)
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# Without using `legend="full"`, the legend only showed years 2014, 2015, 2017, and 2018.
#
# However, there are records from 2016, so we must use `legend="full"`, as done above, to include 2016 data as well.
# In[157]:
sns.set(rc={'figure.figsize':(30,20)})
sns.catplot(data=chi149, x="V_DATE", y="VIOLATIONS", hue="month", palette="rainbow", legend=True)
# ---
# In[309]:
sns.color_palette("husl", 8)
ax = sns.barplot(x="year",
y="VIOLATIONS",
hue="CAMERA_ID",
data=chi149,
errcolor="lightgray",
errwidth=1
)
ax
# We can see that the number of violations was indeed the highest during months 6-8 (June-August) of 2015.
#
# We can also see that during each year, there is a peak in violations during the Summer months and then a reduction during the Fall/Winter months.
#
# It is possible that the neighborhood is extra crowded during the Summer and less during the Winter.
#
# It could be the case that the Summer heat is correlated to poorer focus of the drivers, leading to more violations.
#
# It is important to look into the area and observe changes.
# ---
# In[ ]:
# In[150]:
chi149.V_DATE #[0:((chi149.V_DATE.count())/2)] / returns decimal. but cant use decimal for slicing index.
# In[75]:
chi149.V_DATE[0:(chi149.V_DATE.count()//2)] # 753 rows
# In[76]:
10/2 # 5.0
# In[77]:
10//2 # 5
# In[52]:
chi149.V_DATE.count()
# In[106]:
chi149.V_DATE[0:1506]
# In[53]:
chi149.VIOLATIONS.count()
# In[56]:
chi149.VIOLATIONS[1506:]
# In[50]:
chi149.V_DATE[0:chi149.V_DATE.count(),]
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[107]:
chi149.VIOLATIONS.count()
# In[108]:
chi149.VIOLATIONS[chi149.VIOLATIONS.count()]
# In[ ]:
# In[ ]:
# In[22]:
df['CAMERA_ID'].value_counts().sort_index()
# 162 diff cameras in total (shown by Length: 162 below the series above.)
# In[ ]:
# In[ ]:
# In[23]:
len(df.V_DATE.value_counts()) # 1637
len(df.ADDRESS.value_counts()) # 163
len(df.CAMERA_ID.value_counts()) # 162
# In[24]:
min(df.V_DATE)
# ?? '01/01/2015' but actually it is 7/1/2014 .. wrong order because month is taken
# ?? into consideration first, followed by date, then year.
max(df.V_DATE)
# '12/31/2017'
# In[ ]:
# In[25]:
address = pd.DataFrame(df.groupby('ADDRESS').size().sort_values(ascending=False))
address.rename(columns={0:'FREQUENCY AT GIVEN ADDRESS'})
# In[ ]:
# In[26]:
pd.DataFrame(df.groupby(['VIOLATIONS', 'CAMERA_ID']).size().sort_index(ascending=False))[0:20].rename(columns={0:'Count of Days on which `CAMERA_ID` caught `VIOLATIONS` number of violations'})
# In[ ]:
# In[27]:
pd.DataFrame(df.groupby(['VIOLATIONS', 'CAMERA_ID']).size()[0:20]).rename(columns={0:'Count of Days on which `CAMERA_ID` caught `VIOLATIONS` number of violations'})
# In[28]:
pd.DataFrame(df.groupby('year').size().sort_values(ascending=False)).sort_index()
# Note: numbers are just number of rows that contain year value of 2014, not the actual number of accidents in 2014. This is further confirmed below.
# In[29]:
df_2014 = df[df.year == 2014]
df_2014
# In[30]:
min(df_2014.month)
# In[31]:
df_7_2014 = df_2014[df_2014.month==7]
# In[32]:
df_7_2014.sort_values(by='date')
# Shortcut:
# In[33]:
df_2014.sort_values(by=['month', 'date'])
# **Proof that 07-01-2014 is the earliest date and not 1-1-2015**
#
# ---
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[34]:
violations = pd.DataFrame(df.groupby('VIOLATIONS').size())
violations.columns=['Number of Occurences of X Violations']
violations
# In[35]:
df['VIOLATIONS'].value_counts().sort_index()[-10:]
# Confirmation: There were 2 instances of **479 violations in just 1 day!**
# In[36]:
df[df.VIOLATIONS==479]
# Interestingly, both those days involved the same `CAMERA_ID` and `ADDRESS`, showing us that this area is a very unsafe area.
# In[37]:
v60 = pd.DataFrame(df[df.VIOLATIONS>60])
v60
# In[38]:
v60_1 = pd.DataFrame(v60.groupby('CAMERA_ID').size().sort_values(ascending=False))
v60_1
df[df.VIOLATIONS>300].groupby('CAMERA_ID').size().sort_values(ascending=False) # number of ROWS, not violations
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]: