#DESARROLLADO POR
#Jarinson Castro
#Data AnalystLos Angeles, California 😎. The City of Angels. Tinseltown. The Entertainment Capital of the World!
Known for its warm weather, palm trees, sprawling coastline, and Hollywood, along with producing some of the most iconic films and songs. However, as with any highly populated city, it isn't always glamorous and there can be a large volume of crime. That's where you can help!
You have been asked to support the Los Angeles Police Department (LAPD) by analyzing crime data to identify patterns in criminal behavior. They plan to use your insights to allocate resources effectively to tackle various crimes in different areas.
The Data
They have provided you with a single dataset to use. A summary and preview are provided below.
It is a modified version of the original data, which is publicly available from Los Angeles Open Data.
crimes.csv
| Column | Description |
|---|---|
'DR_NO' | Division of Records Number: Official file number made up of a 2-digit year, area ID, and 5 digits. |
'Date Rptd' | Date reported - MM/DD/YYYY. |
'DATE OCC' | Date of occurrence - MM/DD/YYYY. |
'TIME OCC' | In 24-hour military time. |
'AREA NAME' | The 21 Geographic Areas or Patrol Divisions are also given a name designation that references a landmark or the surrounding community that it is responsible for. For example, the 77th Street Division is located at the intersection of South Broadway and 77th Street, serving neighborhoods in South Los Angeles. |
'Crm Cd Desc' | Indicates the crime committed. |
'Vict Age' | Victim's age in years. |
'Vict Sex' | Victim's sex: F: Female, M: Male, X: Unknown. |
'Vict Descent' | Victim's descent:
|
'Weapon Desc' | Description of the weapon used (if applicable). |
'Status Desc' | Crime status. |
'LOCATION' | Street address of the crime. |
# Importamos las librerías necesarias y cargamos el csv.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
crimes = pd.read_csv("crimes.csv", dtype={"TIME OCC": str})
crimes.head()- ¿Qué hora tiene la frecuencia de crimen más alta? Registra la hora como entero en la variable peak_crime_hour.
#Primero obtengo los 2 primeros dígitos de la hora que está inicialmente como string.
crimes["HOUR OCC"] = crimes["TIME OCC"].str[:2]
#Convierto la hora obtenido en integer.
crimes["HOUR OCC"] = crimes["HOUR OCC"].astype(int)
#Agrupo por Hora y hago un conteo de los códigos de denuncia.
crimes_gr = crimes.groupby("HOUR OCC",as_index=False)["DR_NO"].count()
#Ordeno el grupo de forma descendiente.
crimes_gr_or = crimes_gr.sort_values("DR_NO",ascending=False)
#Creo la variable solicitada en este proyecto:
peak_crime_hour = crimes_gr_or["HOUR OCC"].values[0]
- ¿Qué área tiene la frecuencia de crímenes más larga?
Registra la hora como string en la variable
peak_night_crime_location.
crimes["TIME OCC"] = crimes["TIME OCC"].astype(int)
crimes_filtered = crimes[(crimes["TIME OCC"]>=2200) ^ (crimes["TIME OCC"]<=359)]
crimes_gr = crimes.groupby("AREA NAME",as_index=False)["DR_NO"].count()
crimes_gr_sr = crimes_gr.sort_values("DR_NO",ascending=False)
peak_night_crime_location = crimes_gr_sr["AREA NAME"].values[0]- Identifica la cantidad de delitos cometidos contra víctimas de diferentes grupos de edad. Guarda el resultado como una Series de pandas llamada victim_ages, utilizando como índice las etiquetas de los grupos de edad "0-17", "18-25", "26-34", "35-44", "45-54", "55-64" y "65+", y la frecuencia de los delitos como los valores.
MÉTODO 1 DE CLASIFICACIÓN
#Primero creo las etiquetas de los grupos según lo requerido para este examen:
etiqueta_grupo = ["0-17","18-25","26-34","35-44","45-54","55-64","65+"]
#Creo los grupos con las edades que debería considerar:
parametros = [-1,17,25,34,44,54,64,np.inf]
#Dato: np.inf es un número infinito que me permite considerar la mayor cantidad de
#edades que sean mayores a los 65, así no tengo que estar escribiendo cada límite manualmente.
#Cruzo todo en una nueva columna donde se alojará la información del grupo.
crimes["vic_class"] = pd.cut(crimes["Vict Age"],labels=etiqueta_grupo,bins=parametros)
#Finalmente, lo dejamos como un pandas Series:
victim_ages = crimes.groupby("vic_class")["DR_NO"].count()
print(victim_ages)
MÉTODO 2 DE CLASIFICACIÓN
#Primero creo las etiquetas de los grupos según lo requerido para este examen:
etiqueta_grupo = ["0-17","18-25","26-34","35-44","45-54","55-64"]
#Creo la condición:
condicion = [
(crimes["Vict Age"]<=17),
(crimes["Vict Age"]>17)&(crimes["Vict Age"]<=25),
(crimes["Vict Age"]>25)&(crimes["Vict Age"]<=34),
(crimes["Vict Age"]>34)&(crimes["Vict Age"]<=44),
(crimes["Vict Age"]>44)&(crimes["Vict Age"]<=54),
(crimes["Vict Age"]>54)&(crimes["Vict Age"]<=64),
]
#Añado con un np.select
crimes["vic_class"] = np.select(condicion,etiqueta_grupo,"65+")
#Finalmente, lo dejamos como un pandas Series:
victim_ages = crimes.groupby("vic_class")["DR_NO"].count()
print(victim_ages)