hyzhang00 commited on
Commit
071cf42
·
verified ·
1 Parent(s): efe30e8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -135
app.py CHANGED
@@ -132,140 +132,5 @@ def main():
132
  top_violations = get_top_violations(df, selected_age)
133
  st.table(top_violations)
134
 
135
- if __name__ == "__main__":
136
- main()import streamlit as st
137
- import pandas as pd
138
- import plotly.express as px
139
-
140
- def load_and_preprocess_data(file_path):
141
- # Read the data
142
- df = pd.read_csv(file_path)
143
-
144
- # Basic preprocessing
145
- df = df.drop(['X', 'Y'], axis=1)
146
- df.dropna(subset=['Incidentid', 'DateTime', 'Year', 'Latitude', 'Longitude'], inplace=True)
147
-
148
- # Fill missing values
149
- numeric = ['Age_Drv1', 'Age_Drv2']
150
- for col in numeric:
151
- df[col].fillna(df[col].median(), inplace=True)
152
-
153
- categorical = ['Gender_Drv1', 'Violation1_Drv1', 'AlcoholUse_Drv1', 'DrugUse_Drv1',
154
- 'Gender_Drv2', 'Violation1_Drv2', 'AlcoholUse_Drv2', 'DrugUse_Drv2',
155
- 'Unittype_Two', 'Traveldirection_Two', 'Unitaction_Two', 'CrossStreet']
156
- for col in categorical:
157
- df[col].fillna('Unknown', inplace=True)
158
-
159
- # Remove invalid ages
160
- df = df[
161
- (df['Age_Drv1'] <= 90) &
162
- (df['Age_Drv2'] <= 90) &
163
- (df['Age_Drv1'] >= 16) &
164
- (df['Age_Drv2'] >= 16)
165
- ]
166
-
167
- # Create age groups
168
- bins = [15, 25, 35, 45, 55, 65, 90]
169
- labels = ['16-25', '26-35', '36-45', '46-55', '56-65', '65+']
170
-
171
- df['Age_Group_Drv1'] = pd.cut(df['Age_Drv1'], bins=bins, labels=labels)
172
- df['Age_Group_Drv2'] = pd.cut(df['Age_Drv2'], bins=bins, labels=labels)
173
-
174
- return df
175
-
176
- def create_severity_violation_chart(df, age_group=None):
177
- # Apply age group filter if selected
178
- if age_group != 'All Ages':
179
- df = df[(df['Age_Group_Drv1'] == age_group) | (df['Age_Group_Drv2'] == age_group)]
180
-
181
- # Combine violations from both drivers
182
- violations_1 = df.groupby(['Violation1_Drv1', 'Injuryseverity']).size().reset_index(name='count')
183
- violations_2 = df.groupby(['Violation1_Drv2', 'Injuryseverity']).size().reset_index(name='count')
184
-
185
- violations_1.columns = ['Violation', 'Severity', 'count']
186
- violations_2.columns = ['Violation', 'Severity', 'count']
187
-
188
- violations = pd.concat([violations_1, violations_2])
189
- violations = violations.groupby(['Violation', 'Severity'])['count'].sum().reset_index()
190
-
191
- # Create visualization
192
- fig = px.bar(
193
- violations,
194
- x='Violation',
195
- y='count',
196
- color='Severity',
197
- title=f'Crash Severity Distribution by Violation Type - {age_group}',
198
- labels={'count': 'Number of Incidents', 'Violation': 'Violation Type'},
199
- height=600
200
- )
201
-
202
- fig.update_layout(
203
- xaxis_tickangle=-45,
204
- legend_title='Severity Level',
205
- barmode='stack'
206
- )
207
-
208
- return fig
209
-
210
- def get_top_violations(df, age_group):
211
- if age_group == 'All Ages':
212
- violations = pd.concat([
213
- df['Violation1_Drv1'].value_counts(),
214
- df['Violation1_Drv2'].value_counts()
215
- ]).groupby(level=0).sum()
216
- else:
217
- filtered_df = df[
218
- (df['Age_Group_Drv1'] == age_group) |
219
- (df['Age_Group_Drv2'] == age_group)
220
- ]
221
- violations = pd.concat([
222
- filtered_df['Violation1_Drv1'].value_counts(),
223
- filtered_df['Violation1_Drv2'].value_counts()
224
- ]).groupby(level=0).sum()
225
-
226
- # Convert to DataFrame and format
227
- violations_df = violations.reset_index()
228
- violations_df.columns = ['Violation Type', 'Count']
229
- violations_df['Percentage'] = (violations_df['Count'] / violations_df['Count'].sum() * 100).round(2)
230
- violations_df['Percentage'] = violations_df['Percentage'].map('{:.2f}%'.format)
231
-
232
- return violations_df.head()
233
-
234
- def main():
235
- st.title('Traffic Crash Analysis')
236
-
237
- # Load data
238
- df = load_and_preprocess_data('1.08_Crash_Data_Report_(detail).csv')
239
-
240
- # Create simple dropdown for age groups
241
- age_groups = ['All Ages', '16-25', '26-35', '36-45', '46-55', '56-65', '65+']
242
- selected_age = st.selectbox('Select Age Group:', age_groups)
243
-
244
- # Create and display chart
245
- fig = create_severity_violation_chart(df, selected_age)
246
- st.plotly_chart(fig, use_container_width=True)
247
-
248
- # Display statistics
249
- if selected_age == 'All Ages':
250
- total_incidents = len(df)
251
- else:
252
- total_incidents = len(df[
253
- (df['Age_Group_Drv1'] == selected_age) |
254
- (df['Age_Group_Drv2'] == selected_age)
255
- ])
256
-
257
- # Create two columns for statistics
258
- col1, col2 = st.columns(2)
259
-
260
- with col1:
261
- st.markdown(f"### Total Incidents")
262
- st.markdown(f"**{total_incidents:,}** incidents for {selected_age}")
263
-
264
- # Display top violations table
265
- with col2:
266
- st.markdown("### Top Violations")
267
- top_violations = get_top_violations(df, selected_age)
268
- st.table(top_violations)
269
-
270
  if __name__ == "__main__":
271
  main()
 
132
  top_violations = get_top_violations(df, selected_age)
133
  st.table(top_violations)
134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  if __name__ == "__main__":
136
  main()