namdini commited on
Commit
7369ec9
·
verified ·
1 Parent(s): 30f4961

Create app2.py

Browse files
Files changed (1) hide show
  1. app2.py +199 -0
app2.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import plotly.express as px
4
+ import altair as alt
5
+
6
+ def load_and_preprocess_data(file_path):
7
+ # Read the data
8
+ df = pd.read_csv(file_path)
9
+
10
+ # Basic preprocessing
11
+ df = df.drop(['X', 'Y'], axis=1)
12
+ df.dropna(subset=['Incidentid', 'DateTime', 'Year', 'Latitude', 'Longitude'], inplace=True)
13
+
14
+ # Convert Year to int
15
+ df['Year'] = df['Year'].astype(int)
16
+
17
+ # Fill missing values
18
+ numeric = ['Age_Drv1', 'Age_Drv2']
19
+ for col in numeric:
20
+ df[col].fillna(df[col].median(), inplace=True)
21
+
22
+ categorical = ['Gender_Drv1', 'Violation1_Drv1', 'AlcoholUse_Drv1', 'DrugUse_Drv1',
23
+ 'Gender_Drv2', 'Violation1_Drv2', 'AlcoholUse_Drv2', 'DrugUse_Drv2',
24
+ 'Unittype_Two', 'Traveldirection_Two', 'Unitaction_Two', 'CrossStreet']
25
+ for col in categorical:
26
+ df[col].fillna('Unknown', inplace=True)
27
+
28
+ # Remove invalid ages
29
+ df = df[
30
+ (df['Age_Drv1'] <= 90) &
31
+ (df['Age_Drv2'] <= 90) &
32
+ (df['Age_Drv1'] >= 16) &
33
+ (df['Age_Drv2'] >= 16)
34
+ ]
35
+
36
+ # Create age groups
37
+ bins = [15, 25, 35, 45, 55, 65, 90]
38
+ labels = ['16-25', '26-35', '36-45', '46-55', '56-65', '65+']
39
+
40
+ df['Age_Group_Drv1'] = pd.cut(df['Age_Drv1'], bins=bins, labels=labels)
41
+ df['Age_Group_Drv2'] = pd.cut(df['Age_Drv2'], bins=bins, labels=labels)
42
+
43
+ return df
44
+
45
+ def create_severity_violation_chart(df, age_group=None):
46
+ # Apply age group filter if selected
47
+ if age_group != 'All Ages':
48
+ df = df[(df['Age_Group_Drv1'] == age_group) | (df['Age_Group_Drv2'] == age_group)]
49
+
50
+ # Combine violations from both drivers
51
+ violations_1 = df.groupby(['Violation1_Drv1', 'Injuryseverity']).size().reset_index(name='count')
52
+ violations_2 = df.groupby(['Violation1_Drv2', 'Injuryseverity']).size().reset_index(name='count')
53
+
54
+ violations_1.columns = ['Violation', 'Severity', 'count']
55
+ violations_2.columns = ['Violation', 'Severity', 'count']
56
+
57
+ violations = pd.concat([violations_1, violations_2])
58
+ violations = violations.groupby(['Violation', 'Severity'])['count'].sum().reset_index()
59
+
60
+ # Create visualization
61
+ fig = px.bar(
62
+ violations,
63
+ x='Violation',
64
+ y='count',
65
+ color='Severity',
66
+ title=f'Crash Severity Distribution by Violation Type - {age_group}',
67
+ labels={'count': 'Number of Incidents', 'Violation': 'Violation Type'},
68
+ height=600
69
+ )
70
+
71
+ fig.update_layout(
72
+ xaxis_tickangle=-45,
73
+ legend_title='Severity Level',
74
+ barmode='stack'
75
+ )
76
+
77
+ return fig
78
+
79
+ def get_top_violations(df, age_group):
80
+ if age_group == 'All Ages':
81
+ violations = pd.concat([
82
+ df['Violation1_Drv1'].value_counts(),
83
+ df['Violation1_Drv2'].value_counts()
84
+ ]).groupby(level=0).sum()
85
+ else:
86
+ filtered_df = df[
87
+ (df['Age_Group_Drv1'] == age_group) |
88
+ (df['Age_Group_Drv2'] == age_group)
89
+ ]
90
+ violations = pd.concat([
91
+ filtered_df['Violation1_Drv1'].value_counts(),
92
+ filtered_df['Violation1_Drv2'].value_counts()
93
+ ]).groupby(level=0).sum()
94
+
95
+ # Convert to DataFrame and format
96
+ violations_df = violations.reset_index()
97
+ violations_df.columns = ['Violation Type', 'Count']
98
+ violations_df['Percentage'] = (violations_df['Count'] / violations_df['Count'].sum() * 100).round(2)
99
+ violations_df['Percentage'] = violations_df['Percentage'].map('{:.2f}%'.format)
100
+
101
+ return violations_df.head()
102
+
103
+ def create_injuries_fatalities_chart(crash_data):
104
+ # Filter rows where we have valid data for all necessary columns
105
+ crash_data = crash_data[['DateTime', 'Totalinjuries', 'Totalfatalities', 'Unittype_One', 'Unittype_Two']].dropna()
106
+
107
+ # Convert "DateTime" to datetime type
108
+ crash_data['DateTime'] = pd.to_datetime(crash_data['DateTime'], errors='coerce')
109
+ crash_data['Month'] = crash_data['DateTime'].dt.month_name()
110
+
111
+ # sort months in order
112
+ month_order = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
113
+ crash_data['Month'] = pd.Categorical(crash_data['Month'], categories=month_order, ordered=True)
114
+
115
+ # Dropdown for Unit Type selection
116
+ unit_type_pairs = set()
117
+ for _, row in crash_data[['Unittype_One', 'Unittype_Two']].dropna().iterrows():
118
+ if row['Unittype_One'] != 'Driverless' or row['Unittype_Two'] != 'Driverless':
119
+ pair = ' vs '.join(sorted([row['Unittype_One'], row['Unittype_Two']]))
120
+ unit_type_pairs.add(pair)
121
+ unit_type_pairs = sorted(list(unit_type_pairs))
122
+ unit_type = st.selectbox("Select Unit Type Pair", options=['Total'] + unit_type_pairs)
123
+
124
+ # Filter data based on the selected unit type
125
+ if unit_type == 'Total':
126
+ filtered_data = crash_data
127
+ else:
128
+ unit_one, unit_two = unit_type.split(' vs ')
129
+ filtered_data = crash_data[((crash_data['Unittype_One'] == unit_one) & (crash_data['Unittype_Two'] == unit_two)) |
130
+ ((crash_data['Unittype_One'] == unit_two) & (crash_data['Unittype_Two'] == unit_one))]
131
+
132
+ # Group data by month and calculate total injuries and fatalities
133
+ monthly_sum = filtered_data.groupby('Month').agg({'Totalinjuries': 'sum', 'Totalfatalities': 'sum'}).reset_index()
134
+
135
+ # Reshape the data for easier plotting
136
+ injuries = monthly_sum[['Month', 'Totalinjuries']].rename(columns={'Totalinjuries': 'Value'})
137
+ injuries['Measure'] = 'Total Injuries'
138
+
139
+ fatalities = monthly_sum[['Month', 'Totalfatalities']].rename(columns={'Totalfatalities': 'Value'})
140
+ fatalities['Measure'] = 'Total Fatalities'
141
+
142
+ combined_data = pd.concat([injuries, fatalities])
143
+
144
+ # Plot line chart
145
+ line_chart = alt.Chart(combined_data).mark_line(point=True).encode(
146
+ x=alt.X('Month:N', sort=month_order, title='Month'),
147
+ y=alt.Y('Value:Q', title='Total Injuries & Fatalities'),
148
+ color=alt.Color('Measure:N', title='', scale=alt.Scale(domain=['Total Injuries', 'Total Fatalities'], range=['blue', 'red'])),
149
+ tooltip=['Month', 'Measure:N', 'Value:Q']
150
+ ).properties(
151
+ title=f'Total Injuries and Fatalities by Month for Unit Type Pair: {unit_type}',
152
+ width=600,
153
+ height=400
154
+ )
155
+
156
+ return line_chart
157
+
158
+ def main():
159
+ st.title('Traffic Crash Analysis')
160
+
161
+ # Load data
162
+ df = load_and_preprocess_data('1.08_Crash_Data_Report_(detail).csv')
163
+
164
+ # Create simple dropdown for age groups
165
+ age_groups = ['All Ages', '16-25', '26-35', '36-45', '46-55', '56-65', '65+']
166
+ selected_age = st.selectbox('Select Age Group:', age_groups)
167
+
168
+ # Create and display crash severity vs violation type chart
169
+ fig = create_severity_violation_chart(df, selected_age)
170
+ st.plotly_chart(fig, use_container_width=True)
171
+
172
+ # Create and display injuries and fatalities chart
173
+ injuries_fatalities_chart = create_injuries_fatalities_chart(df)
174
+ st.altair_chart(injuries_fatalities_chart, use_container_width=True)
175
+
176
+ # Display statistics
177
+ if selected_age == 'All Ages':
178
+ total_incidents = len(df)
179
+ else:
180
+ total_incidents = len(df[
181
+ (df['Age_Group_Drv1'] == selected_age) |
182
+ (df['Age_Group_Drv2'] == selected_age)
183
+ ])
184
+
185
+ # Create two columns for statistics
186
+ col1, col2 = st.columns(2)
187
+
188
+ with col1:
189
+ st.markdown(f"### Total Incidents")
190
+ st.markdown(f"**{total_incidents:,}** incidents for {selected_age}")
191
+
192
+ # Display top violations table
193
+ with col2:
194
+ st.markdown("### Top Violations")
195
+ top_violations = get_top_violations(df, selected_age)
196
+ st.table(top_violations)
197
+
198
+ if __name__ == "__main__":
199
+ main()