Proyecto Individual N.2 / Data Analytics
Mi rol como data analist es encontrar indicios o patrones en los datos que luego sirvan para la toma de decisiones. En este caso el dataset a estudiar incluye informacion de accidentes viales en la zona de CABA Argentina, ocurridos entre 2016 y 2021.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# Load the vial.xlsx file
df_vial = pd.read_excel('vial.xlsx')
# Check for missing values
missing_values = df_vial.isnull().sum()
print("Missing values:\n", missing_values)
# Check for duplicates
duplicates = df_vial.duplicated().sum()
print("Number of duplicates:", duplicates)
# Drop columns 'Altura' and 'Cruce' from dataframe df_vial
#df_vial.drop(['Altura', 'Cruce'], axis=1, inplace=True)
df_vial.head()
df_vial.info()
Data Cleaning Steps for DataFrame df_vial
Based on the information provided, here are some data cleaning steps that can be performed on the DataFrame df_vial
:
-
Handling Missing Values:
- Identify columns with missing values and decide on an appropriate strategy to handle them (e.g., imputation, deletion).
-
Dropping Unnecessary Columns:
- Remove columns that are not relevant for the analysis or contain redundant information.
-
Handling Duplicates:
- Identify and remove any duplicate rows in the DataFrame.
-
Standardizing Data:
- Check for inconsistent or incorrect data formats and standardize them if necessary.
-
Renaming Columns:
- Rename columns with unclear or inconsistent names to improve clarity and consistency.
-
Data Type Conversion:
- Convert columns to their appropriate data types if needed (e.g., datetime, numeric).
These are general steps, and the specific cleaning requirements may vary based on the analysis goals and the characteristics of the dataset.
# Rename columns 'Dirección Normalizada' to 'DIRNORM', 'pos x' to 'LONGITUD', and 'pos y' to 'LATITUD'
df_vial.rename(columns={'Dirección Normalizada': 'DIRNORM', 'pos x': 'LONGITUD', 'pos y': 'LATITUD'}, inplace=True)
df_vial.columns
import plotly.graph_objects as go
# Agrupa los datos por la columna 'VICTIMA' y suma el número de víctimas en cada categoría
data_grouped = df_vial.groupby('VICTIMA')['N_VICTIMAS'].sum().reset_index()
# Ordenar los datos por el número de víctimas de forma descendente
data_grouped.sort_values('N_VICTIMAS', ascending=False, inplace=True)
# Obtener los 4 valores más importantes y el resto
top_4 = data_grouped.head(4)
rest = data_grouped.iloc[4:]
# Crear el gráfico de torta para los 4 valores más importantes
fig1 = go.Figure(data=[go.Pie(labels=top_4['VICTIMA'], values=top_4['N_VICTIMAS'])])
fig1.update_layout(title='Víctimas por Categoría (Top 4)', height=400, width=400)
# Crear el gráfico de torta para el resto de valores
fig2 = go.Figure(data=[go.Pie(labels=rest['VICTIMA'], values=rest['N_VICTIMAS'])])
fig2.update_layout(title='Víctimas por Categoría (Resto)', height=400, width=400)
# Mostrar los gráficos
fig1.show()
fig2.show()
import pandas as pd
import matplotlib.pyplot as plt
df_vial = pd.read_csv('df_vial.csv')
# Agrupa los datos por la columna 'VICTIMA' y suma el número de víctimas en cada categoría
data_grouped = df_vial.groupby('VICTIMA')['N_VICTIMAS'].sum().reset_index()
# Ordenar los datos por el número de víctimas de forma descendente
data_grouped.sort_values('N_VICTIMAS', ascending=False, inplace=True)
# Obtener los 4 valores más importantes y el resto
top_4 = data_grouped.head(4)
rest = data_grouped.iloc[4:]
# Crear el gráfico de torta para los 4 valores más importantes
fig1, ax1 = plt.subplots()
ax1.pie(top_4['N_VICTIMAS'], labels=top_4['VICTIMA'], autopct='%1.1f%%')
ax1.set_title('Víctimas por Categoría (Top 4)')
# Crear el gráfico de torta para el resto de valores
fig2, ax2 = plt.subplots()
ax2.pie(rest['N_VICTIMAS'], labels=rest['VICTIMA'], autopct='%1.1f%%')
ax2.set_title('Víctimas por Categoría (Resto)')
# Mostrar los gráficos
plt.show()
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
#from qbstyles import mpl_style
#mpl_style(dark = False)
# Aumentar tamaño del grafico
plt.rcParams["figure.figsize"] = (12, 5)
# Load the dataframe from the csv file
df_vial = pd.read_csv('df_vial.csv')
# Group the data by 'HH' and calculate the sum of 'N_VICTIMAS' for each hour
hourly_data = df_vial.groupby('HH')['N_VICTIMAS'].sum().reset_index()
# Sort the data by the sum of 'N_VICTIMAS' in descending order
hourly_data.sort_values('HH', ascending=True, inplace=True)
# Create a scatter plot using seaborn to visualize the relationship between 'HH' and 'N_VICTIMAS'
sns.set_palette("Set2")
sns.barplot(data=hourly_data, x='HH', y='N_VICTIMAS')
# Set the labels and title for the plot
plt.xlabel('Hora')
plt.ylabel('Numero de Victimas')
plt.title('Numero de Victimas por Hora')
# Show the plot
plt.show()
3. Estudiar KPI
Acciones sugeridas:
- Analizar la distribución de accidentes por día de la semana para identificar cualquier patrón.
- Investigar las principales causas de accidentes en la región de CABA y proponer medidas para abordarlas.
- Monitorear la tendencia de los accidentes a lo largo del tiempo e identificar cualquier cambio significativo o aumento repentino.
Siéntete libre de agregar más código o modificar el código existente según tus necesidades.
import pandas as pd
import plotly.express as px
# Convert the 'FECHA' column to datetime format
df_vial['FECHA'] = pd.to_datetime(df_vial['FECHA'])
# Extract the month and year from the 'FECHA' column and create new columns 'MONTH' and 'YEAR'
df_vial['MONTH'] = df_vial['FECHA'].dt.month
df_vial['YEAR'] = df_vial['FECHA'].dt.year
# Group the data by 'YEAR' and 'MONTH' and calculate the total number of accidents in each month
monthly_accidents = df_vial.groupby(['YEAR', 'MONTH'])['N_VICTIMAS'].sum().reset_index()
# Plot the trend of monthly accidents with one line per year
fig1 = px.line(monthly_accidents, x='MONTH', y='N_VICTIMAS', color='YEAR', title='Trend of Monthly Accidents by Year')
fig1.update_xaxes(title='Month')
fig1.update_yaxes(title='Number of Accidents')
# Plot the trend of monthly accidents without different colors for each year
fig2 = px.line(monthly_accidents, x='MONTH', y='N_VICTIMAS', title='Trend of Monthly Accidents')
fig2.update_xaxes(title='MES')
fig2.update_yaxes(title='Numero de Accidentes')
# Show the plots
fig1.show()
#fig2.show()
OBSERVACION TENDENCIA DE ACCIDENTES POR MES:
Hay una aumento de accidentes entre octubre y diciembre, relacionado quizas con las fiestas de navidad y año nuevo.
import pandas as pd
import plotly.express as px
# Convert the 'FECHA' column to datetime format
df_vial['FECHA'] = pd.to_datetime(df_vial['FECHA'])
# Extract the day of the week from the 'FECHA' column and create a new column 'DAY_OF_WEEK'
df_vial['DAY_OF_WEEK'] = df_vial['FECHA'].dt.dayofweek
# Map the day of the week values to their respective names
day_names = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
df_vial['DAY_OF_WEEK'] = df_vial['DAY_OF_WEEK'].map(lambda x: day_names[x])
# Group the data by 'DAY_OF_WEEK' and calculate the total number of accidents on each day
daily_accidents = df_vial.groupby('DAY_OF_WEEK')['N_VICTIMAS'].sum().reset_index()
# Plot the distribution of accidents by day of the week
fig = px.histogram(daily_accidents, x='DAY_OF_WEEK', y='N_VICTIMAS', title='Distribución de accidentes por día de la semana')
fig.update_xaxes(title='Day of the Week')
fig.update_yaxes(title='Number of Accidents')
# Show the plot
fig.show()