Los 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. |
# Re-run this cell
# Import required libraries
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()Which hour has the highest frequency of crimes?
crimes['TIME_OCC_TIME'] = pd.to_datetime(crimes['TIME OCC'].str.zfill(4), format='%H%M')
crimes['TIME_OCC_hour']=crimes['TIME_OCC_TIME'].dt.hour
y1=crimes.groupby("TIME_OCC_hour")['DR_NO'].count()
sns.set_palette("Set2")
sns.set_style("whitegrid")
g=sns.barplot(y1)
g.set_title(" times_of_the_day VS count_of_crimes ")
g.set(ylabel="count_of_crimes")
#from the fig we see that peak_crime_hour is 12
peak_crime_hour = 12
Which area has the largest frequency of night crimes (crimes committed between 10pm and 3:59am)
from datetime import time
import seaborn as sns
import matplotlib.pyplot as plt
night_crimes = crimes[
(crimes['TIME_OCC_TIME'].dt.time >= time(22, 0)) | # 10:00 PM to 11:59 PM
(crimes['TIME_OCC_TIME'].dt.time < time(4, 0)) # 12:00 AM to 3:59 AM
]
y = night_crimes["AREA NAME"].value_counts()
sns.set_palette("Set2")
sns.set_style("whitegrid")
g = sns.barplot(x=y.index, y=y.values)
g.set_title("AREA_NAME VS count_of_night_crimes")
g.set(ylabel="count_of_night_crimes")
plt.xticks(rotation=90)
plt.show()#from the fig we see that peak_night_crime_area is Central
peak_night_crime_location = "Central"Identify the number of crimes committed against victims of different age groups.
labels=["0-17", "18-25", "26-34", "35-44", "45-54", "55-64","65+"]
bins = [0, 17, 25, 34, 44, 54, 64, 200]
crimes["AGE_GROUPS"] =pd.cut(crimes['Vict Age'], bins=bins, labels=labels, right=True, include_lowest=True)
y= crimes["AGE_GROUPS"].value_counts()
sns.set_palette("Set2")
sns.set_style("whitegrid")
g = sns.barplot(x=y.index, y=y.values)
g.set_title("count of victims age groups ")
g.set(xlabel="age groups",
ylabel="count of age groups")
plt.show()y2 = crimes.groupby(["TIME_OCC_hour", "Vict Sex"])['DR_NO'].count().reset_index()
plt.figure(figsize=(14, 8))
sns.set_palette("Set2")
sns.set_style("whitegrid")
g = sns.barplot(data=y2, x="TIME_OCC_hour", y="DR_NO", hue="Vict Sex")
g.set_title("Number of Crimes by Hour and Victim Sex")
g.set(xlabel="Hour of the Day", ylabel="Number of Crimes")
plt.legend(title="Victim Sex", labels=["Female", "Male"])
plt.xticks(rotation=90)
# Add lines for male and female
for sex in y2['Vict Sex'].unique():
subset = y2[y2['Vict Sex'] == sex]
plt.plot(subset['TIME_OCC_hour'], subset['DR_NO'], marker='o', label=f"Line for {sex}")
plt.show()Before 12 PM, more crimes involve female victims, After 12 PM, more crimes involve male victims.
def map_crime_category(desc):
if "ASSAULT" in desc or "BATTERY" in desc or "THREATS" in desc:
return "Violent Crime"
elif "BURGLARY" in desc or "ROBBERY" in desc or "THEFT" in desc or "BUNCO" in desc or "SHOPLIFTING" in desc or "LARCENY" in desc:
return "Property Crime"
elif "SEX" in desc or "RAPE" in desc or "ORAL COPULATION" in desc or "INDECENT" in desc:
return "Sex Crime"
elif "DRUG" in desc or "PIMPING" in desc or "PANDERING" in desc or "HUMAN TRAFFICKING" in desc:
return "Drug or Exploitation"
elif "VEHICLE" in desc or "MOTOR VEHICLE" in desc or "CAR" in desc:
return "Vehicle Crime"
elif "FRAUD" in desc or "EMBEZZLEMENT" in desc or "FORGERY" in desc or "CREDIT CARD" in desc:
return "Fraud / Financial Crime"
elif "VANDALISM" in desc or "ARSON" in desc or "TRESPASSING" in desc:
return "Public Order Crime"
elif "COURT ORDER" in desc or "RESTRAINING ORDER" in desc or "CONTEMPT" in desc:
return "Legal / Restraining Violations"
elif "STALKING" in desc or "KIDNAPPING" in desc or "FALSE IMPRISONMENT" in desc:
return "Personal Freedom Crime"
elif "WEAPON" in desc or "SHOTS FIRED" in desc or "FIREARMS" in desc:
return "Weapons / Firearms Crime"
else:
return "Other / Misc"
# Apply it to your DataFrame
crimes['CRIME_CATEGORY'] = crimes['Crm Cd Desc'].apply(map_crime_category)
crimes['CRIME_CATEGORY'].value_counts()
grouped = crimes.groupby(["TIME_OCC_hour", "CRIME_CATEGORY", "Vict Sex"])['DR_NO'].count().reset_index(name='COUNT')
g = sns.FacetGrid(
grouped,
col='CRIME_CATEGORY',
col_wrap=2,
height=5,
sharey=False
)
sex_order = ['F', 'M', 'X', 'H']
palette = {
'F': '#66c2a5', # green
'M': '#fc8d62', # orange
'X': '#8da0cb', # blue
'H': '#e78ac3' # pink
}
g.map_dataframe(
sns.barplot,
x='TIME_OCC_hour',
y='COUNT',
hue='Vict Sex',
hue_order=sex_order,
palette=palette
)
g.set_titles("{col_name}")
g.set_axis_labels("Hour", "Crime Count")
g.add_legend(title="Victim Sex")
# Set x-axis to show all hours with numbers
for ax in g.axes.flat:
ax.set_xticks(range(24))
ax.set_xticklabels(range(24))
plt.subplots_adjust(top=0.9)
g.fig.suptitle("Crimes by Hour, Category, and Victim Sex", fontsize=16)
plt.show()Most crimes occur between 12 PM and 6 PM, with a sharp spike for female victims around noon, especially in personal and sex-related crimes. Male victims dominate in violent, property, and weapon-related crimes, especially during the afternoon and evening. Early morning hours (0–6 AM) see the lowest crime activity across nearly all categories.