Skip to content

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

ColumnDescription
'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:
  • 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
'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})
crimes.head()
crimes.info()

Which hour has the highest frequency of crimes?

# Extract the first two digits of entries in TIME OCC and store it in new column HOUR
crimes['HOUR'] = crimes['TIME OCC'].str[:2]

# Convert to integer
crimes['HOUR'] = crimes['HOUR'].astype(int)
crimes.head()
# Determine the hour with the highest frequency of crimes and display the result
peak_crime_hour = crimes['HOUR'].value_counts().index[0]
print(peak_crime_hour)
# Change the scale
sns.set_context('notebook')

# Change the style
sns.set_style('white')

# Plot frequencies of crime occurrence
freq_plot = sns.countplot(data=crimes, x='HOUR', color='lightgrey')

# Change the color of the highest bar for emphasis
bars = freq_plot.patches
max_height = max([bar.get_height() for bar in bars])
for bar in bars:
    if bar.get_height() == max_height:
        bar.set_facecolor('red')
        
        # Add data label on top of the peak bar
        freq_plot.text(bar.get_x() + bar.get_width() / 2, 
                       bar.get_height() + 180,
                       f"{int(bar.get_height()):,}", 
                       ha='center', fontsize=10, fontweight='bold', color='black')
        break

# Add a title
freq_plot.set_title('Crimes in Los Angeles Peak at 12:00', y=1.05, fontweight='bold')

# Add axis labels
freq_plot.set(xlabel='Hour', ylabel='Number of crimes')

# Format y-axis with thousands separator
freq_plot.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f'{int(x):,}'))

# Show the plot
plt.show()

Which area has the largest frequency of night crimes (crimes committed between 10pm and 3:59am)?

# Filter for night crimes
night_crimes = crimes[(crimes['HOUR'] >= 22) | (crimes['HOUR'] < 4)]
peak_night_crime_location = night_crimes['AREA NAME'].value_counts().index[0]
print(f'Peak night crime area in Los Angeles: {peak_night_crime_location}')
top_5_areas = night_crimes['AREA NAME'].value_counts().index[:5]
print(top_5_areas)
top_5_areas_df = crimes[crimes['AREA NAME'].isin(top_5_areas)]
# Define order by descending counts
area_order = top_5_areas_df['AREA NAME'].value_counts().index

# Plot crimes in the top 5 areas
night_plot = sns.countplot(data=top_5_areas_df, x='AREA NAME', color='darkgrey', order=area_order)

# Change the color of the highest bar for emphasis
bars = night_plot.patches
bars[0].set_facecolor('red')

max_height = max([bar.get_height() for bar in bars])

# Add data labels for each bar
for bar in bars:
    height = bar.get_height()
    
    # Bold only the highest bar's label
    fontweight = 'bold' if height == max_height else 'normal'
    
    night_plot.text(bar.get_x() + bar.get_width() / 2, 
                    height + 200,  # Adjust position slightly above bars
                    f"{int(height):,}", 
                    ha='center', fontsize=10, color='black', fontweight=fontweight)

# Add a title
night_plot.set_title('Night Crime Hotspot: Central Has the Highest Incidents', y=1.05, fontweight='bold')

# Add x-axis label
night_plot.set(xlabel='Area')

# Remove y-axis ticks and labels
night_plot.set_yticks([])  # Removes y-axis ticks
night_plot.set_ylabel("")  # Removes y-axis label

# Show the plot
plt.show()

Number of crimes committed against victims of different age groups

# Define age bins and labels
age_bins = [0, 17, 25, 34, 44, 54, 64, float('inf')]
age_labels = ['0-17', '18-25', '26-34', '35-44', '45-54', '55-64', '65+']

# Create a new column AGE_GRP with the age groups
crimes['AGE_GRP'] = pd.cut(crimes['Vict Age'], bins=age_bins, labels=age_labels, right=True)

# Display the first few rows to verify the new column
crimes.head()
‌
‌
‌