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", parse_dates=["Date Rptd", "DATE OCC"], dtype={"TIME OCC": str})
# Hour Crime Occured
crime_hours = crimes['TIME OCC'].str[:2].astype(int)
crimes['HOUR OCC'] = crime_hours
# Age Bracket of Criminals
age_bins = [0, 17, 25, 34, 44, 54, 64, np.inf]
age_labels = ['0-17','18-25','26-34','35-44','45-54','55-64','65+']
crimes['Age Bracket'] = pd.cut(crimes['Vict Age'], age_bins, labels=age_labels)
# Victim Descent
desc_map = {'A': 'Other Asian', 'B': 'Black', 'C': 'Chinese', 'D': 'Cambodian', 'F': 'Filipino', 'G': 'Guamanian', 'H': 'Hispanic/Latin/Mexican', 'I': 'American Indian/Alaskan Native', 'J': 'Japanese', 'K': 'Korean', 'L': 'Laotian', 'O': 'Other', 'P': 'Pacific Islander', 'S': 'Samoan', 'U': 'Hawaiian', 'V': 'Vietnamese', 'W': 'White', 'X': 'Unknown', 'Z': 'Asian Indian'}
crimes['VictDESCFull'] = crimes['Vict Descent'].map(desc_map)
crimes.head()
# Extract date from datetime in the 'DATE OCC' column
crimes['DATE OCC DATE'] = crimes['DATE OCC'].dt.date
crimes['DATE OCC MONTH'] = crimes['DATE OCC'].dt.month
month_map = {1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December'}
crimes['MONTH NAME'] = crimes['DATE OCC MONTH'].map(month_map)
crime_date = crimes.groupby('DATE OCC DATE')['DR_NO'].count().sort_values(ascending=False)
crime_month = crimes.groupby('MONTH NAME')['DR_NO'].count().sort_values(ascending=False)
plt.figure(figsize=(8,12))
plt.subplot(2,1,1)
sns.barplot(data=crime_date.iloc[:10], palette='husl')
plt.xticks(rotation=45)
plt.subplot(2,1,2)
sns.barplot(data=crime_month, palette='husl')
plt.xticks(rotation=45)
plt.show()
# Define a mapping of integers to string values
month_map = {
1: 'January',
2: 'February',
3: 'March',
4: 'April',
5: 'May',
6: 'June',
7: 'July',
8: 'August',
9: 'September',
10: 'October',
11: 'November',
12: 'December'
}
# Apply the mapping to the 'DATE OCC MONTH' column to create a new column 'MONTH NAME'
crimes['MONTH NAME'] = crimes['DATE OCC MONTH'].map(month_map)
# Display the first few rows to verify the new column
crimes.head()
# Highest Frequency Crime Hour
freq = crimes.groupby('HOUR OCC')['DR_NO'].count().sort_values(ascending=False)
peak_crime_hour = freq.index[0]
freq = freq.rename('FREQ')
freq
# Areas and Frequency of Night (10pm - 3:59am) Crimes
night_crimes = crimes[(crimes['HOUR OCC'] < 4) | (crimes['HOUR OCC'] > 22)]
night_crimes_area = night_crimes.groupby('AREA NAME')['DR_NO'].count().sort_values(ascending=False)
night_crimes_area = night_crimes_area.rename('FREQ')
sns.barplot(data=night_crimes_area, palette='husl')
plt.xticks(rotation=90)
plt.show()
#display(night_crimes_area)
# Central
central = crimes[crimes['AREA NAME'] == 'Central']
central_ages = central.groupby('Age Bracket')['DR_NO'].count().sort_values(ascending=False)
central_desc = central.groupby('VictDESCFull')['DR_NO'].count().sort_values(ascending=False)
central_trend = central.groupby('HOUR OCC')['DR_NO'].count()
#plt.figure(figsize=(12,12))
#plt.subplot(2,2,1)
#sns.barplot(data=central_ages, palette='husl')
#plt.subplot(2,2,2)
#sns.barplot(data=central_desc.iloc[:5], palette='husl')
#plt.xticks(rotation=45)
#plt.subplot(2,2,3)
sns.lineplot(data=central_trend, color='black')
sns.scatterplot(data=central_trend, color='red')
plt.title('Central LA\nCrime Trend By Hour Over 24 Hours', weight='bold', fontsize=13)
plt.xlabel('Hour of Day', weight='bold', style='italic')
plt.ylabel('No. of Crimes', weight='bold', style='italic')
plt.xticks(np.arange(0,24,1))
plt.show()
#display(central_ages)
#display(central_desc.iloc[:5])
#central_trend
# Hollywood
sw = crimes[crimes['AREA NAME'] == 'Southwest']
sw_ages = sw.groupby('Age Bracket')['DR_NO'].count().sort_values(ascending=False)
sw_desc = sw.groupby('VictDESCFull')['DR_NO'].count().sort_values(ascending=False)
plt.figure(figsize=(7,11))
plt.subplot(2,1,1)
sns.barplot(data=sw_ages, palette='husl')
plt.title('Age Spread of Victims in Southwest', weight='bold', fontsize=14)
plt.xlabel('Age Bracket', weight='bold', style='italic')
plt.ylabel('No. of Victims', weight='bold', style='italic')
plt.subplot(2,1,2)
swx = sns.barplot(data=sw_desc.iloc[:5], palette='husl')
wrapped_labels = wrap_labels(swx.get_xticklabels(), '/')
swx.set_xticklabels(wrapped_labels)
plt.title('Top 5 Victim Descents in Southwest', weight='bold', fontsize=14)
plt.xlabel('Victim Descent', weight='bold', style='italic')
plt.ylabel('No. of Victims', weight='bold', style='italic')
night_crimes_central = night_crimes[night_crimes['AREA NAME'] == 'Central']
night_crimes_central
# Areas and Frequency of Crimes
crimes_freq = crimes.groupby('AREA NAME')['DR_NO'].count().sort_values(ascending=False)
sns.barplot(data=crimes_freq, palette='husl')
plt.xticks(rotation=90)
plt.show()
crimes_freq
victim_ages = crimes.groupby('Age Bracket')['DR_NO'].count()
victim_ages = victim_ages.rename('FREQ')
sns.barplot(data=victim_ages, palette='husl')
victim_ages
vict_desc = crimes.groupby('VictDESCFull')['DR_NO'].count().sort_values(ascending=False)
ax = sns.barplot(data=vict_desc.iloc[:5], palette='husl')
# Define a wrap function for long labels
def wrap_labels(labels, split_char):
return ['\n'.join([part + split_char if i < len(parts) - 1 else part
for i, part in enumerate(parts)])
for label in labels
for parts in [label.get_text().split(split_char)]]
# Set x-tick labels with wrapping
wrapped_labels = wrap_labels(ax.get_xticklabels(), '/')
ax.set_xticklabels(wrapped_labels)
#vict_desc