# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# analysis factors of traffic accidents

# +
# -*- coding: utf-8 -*- 
# %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pandas import *
import seaborn as sns
from dbfread import DBF
import shelve
import warnings
warnings.filterwarnings('ignore')

plt.style.use('seaborn-dark')
plt.rcParams['figure.figsize'] = (10, 6)
# -

accidents=pd.read_hdf('results/accidents.h5', 'accidents')
vehicles=pd.read_hdf('results/vehicles.h5', 'vehicles')

person=[]
for i,j in zip(range(2007,2017),range(0,10)):
    person.append(DataFrame(iter(DBF("data/person/person{}.dbf".format(i)))))
    person[j]['YEAR']=i
all_person =pd.concat(person, axis=0,join='inner')
person=all_person[['AGE','SEX','DEATH_YR','ST_CASE','STATE','YEAR']]
person.rename(columns={'ST_CASE':'CASE_NUM'},inplace=True)
def make_index(df):
    df['STATE']=df['STATE'].astype(int)
    df['CASE_NUM']=df['CASE_NUM'].astype(int)
    df['YEAR']=df['YEAR'].astype(int)
    df.index = list(df['YEAR'].astype(str) + df['CASE_NUM'].astype(str))
person=make_index(person)

vehicles.head()

fatal_crashs_all = pd.merge(accidents, person, how='inner',on=('STATE', 'YEAR','CASE_NUM'))
fatal_crashs_all.head()

#the total accidents number each year, analysis the difference between every year
year_acci=accidents[['YEAR','CASE_NUM']].groupby('YEAR').count()
month_acci=accidents[['MONTH','CASE_NUM']].groupby('MONTH').count()
day_acci=accidents[['DAY_WEEK','CASE_NUM']].groupby('DAY_WEEK').count()
hour_acci=accidents[['HOUR','CASE_NUM']].groupby('HOUR').count()
hour_acci=hour_acci.drop(hour_acci.index[-1])
hour_acci.iloc[0]=hour_acci.iloc[0]+hour_acci.iloc[-1]
hour_acci=hour_acci.drop(hour_acci.index[-1])
day_acci.index = pd.CategoricalIndex(day_acci.index, 
                               categories=['Monday', 'Tuesday', 'Wednesday', 'Thursday','Friday','Saturday', 'Sunday'], 
                               sorted=True)
day_acci = day_acci.sort_index()
month_acci.index=pd.CategoricalIndex(month_acci.index, 
                               categories=['January', 'February', 'March', 'April','May','June', 'July','August','September','October','November','December'], 
                               sorted=True)
month_acci=month_acci.sort_index()

# +
import matplotlib.pyplot as plt
f1,axarr = plt.subplots(2,2)
f1.set_figwidth(15)
f1.set_figheight(9)

axarr[0,0].set_ylabel("count")
axarr[0,0].set_title("the total accidents number each year")
axarr[0,0].bar(year_acci.index,year_acci['CASE_NUM'])


objects1=np.array(month_acci.index)
x1=np.arange(len(objects1))
axarr[0,1].set_ylabel("count")
axarr[0,1].set_title("the total accidents number every month")
axarr[0,1].bar(x1,month_acci['CASE_NUM'])
axarr[0,1].set_xticks(x1)
axarr[0,1].set_xticklabels(objects1)

axarr[1,0].set_ylabel("count")
axarr[1,0].set_title("the total accidents number every hour")
axarr[1,0].bar(hour_acci.index,hour_acci['CASE_NUM'])
axarr[1,0].set_xticks(np.arange(0,24))

objects2=np.array(day_acci.index)
x2=np.arange(len(objects2))
axarr[1,1].set_ylabel("count")
axarr[1,1].set_title("the total accidents number every week")
axarr[1,1].bar(x2,day_acci['CASE_NUM'])
axarr[1,1].set_xticks(x2)
axarr[1,1].set_xticklabels(objects2)
f1.savefig("fig/time_relate_count.png")
# -

fatal_crashs_all.columns

vehicles.columns

import seaborn as sns
sns.set(style="ticks")
df = sns.load_dataset("iris")
sns.pairplot(df, hue="species")


g=sns.factorplot(x="LIGHT_CONDITION", y="DEATHS", hue="DR_DRINK",col="YEAR",data=vehicles, kind="violin", split=True,col_wrap=3,size=3,aspect=2)
g.set_axis_labels("light_condition", "deaths")










StarcoderdataJupyterScriptsDedupFiltered