Project: Analyzing Crime in Los Angeles

Los Angeles skyline

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})
crimes.head()

DR_NO

Date Rptd

DATE OCC

TIME OCC

AREA NAME

Crm Cd Desc

Vict Age

Vict Sex

Vict Descent

Weapon Desc

Status Desc

LOCATION

0

221412410

2022-06-15

2020-11-12

1700

Pacific

THEFT FROM MOTOR VEHICLE - PETTY ($950 & UNDER)

0

NaN

NaN

NaN

Invest Cont

13600 MARINA POINT DR

1

220314085

2022-07-22

2020-05-12

1110

Southwest

THEFT OF IDENTITY

27

F

B

NaN

Invest Cont

2500 S SYCAMORE AV

2

222013040

2022-08-06

2020-06-04

1620

Olympic

THEFT OF IDENTITY

60

M

H

NaN

Invest Cont

3300 SAN MARINO ST

3

220614831

2022-08-18

2020-08-17

1200

Hollywood

THEFT OF IDENTITY

28

M

H

NaN

Invest Cont

1900 TRANSIENT

4

231207725

2023-02-27

2020-01-27

0635

77th Street

THEFT OF IDENTITY

37

M

H

NaN

Invest Cont

6200 4TH AV

Task 1

Which hour has the highest frequency of crimes? Store as an integer variable called peak_crime_hour.

# Start coding here
# Use as many cells as you need
peak_crime_hour=(crimes.value_counts("TIME OCC").idxmax())
peak_crime_hour=int(peak_crime_hour[:2])

Task 2

Which area has the largest frequency of night crimes (crimes committed between 10pm and 3:59am)? Save as a string variable called peak_night_crime_location.

# Convert TIME OCC as date time
crimes["TimeOcc_int"] = crimes["TIME OCC"].astype("int")
crimes.head(5)

DR_NO

Date Rptd

DATE OCC

TIME OCC

AREA NAME

Crm Cd Desc

Vict Age

Vict Sex

Vict Descent

Weapon Desc

Status Desc

LOCATION

TimeOcc_int

0

221412410

2022-06-15

2020-11-12

1700

Pacific

THEFT FROM MOTOR VEHICLE - PETTY ($950 & UNDER)

0

NaN

NaN

NaN

Invest Cont

13600 MARINA POINT DR

1700

1

220314085

2022-07-22

2020-05-12

1110

Southwest

THEFT OF IDENTITY

27

F

B

NaN

Invest Cont

2500 S SYCAMORE AV

1110

2

222013040

2022-08-06

2020-06-04

1620

Olympic

THEFT OF IDENTITY

60

M

H

NaN

Invest Cont

3300 SAN MARINO ST

1620

3

220614831

2022-08-18

2020-08-17

1200

Hollywood

THEFT OF IDENTITY

28

M

H

NaN

Invest Cont

1900 TRANSIENT

1200

4

231207725

2023-02-27

2020-01-27

0635

77th Street

THEFT OF IDENTITY

37

M

H

NaN

Invest Cont

6200 4TH AV

635

crimes_10pm_to_4am = crimes[((crimes["TimeOcc_int"]>=2200) & (crimes["TimeOcc_int"]<=2400))|((crimes["TimeOcc_int"]>=0) & (crimes["TimeOcc_int"]<=400))]
crimes_10pm_to_4am.columns
Index(['DR_NO', 'Date Rptd', 'DATE OCC', 'TIME OCC', 'AREA NAME',
       'Crm Cd Desc', 'Vict Age', 'Vict Sex', 'Vict Descent', 'Weapon Desc',
       'Status Desc', 'LOCATION', 'TimeOcc_int'],
      dtype='object')
peak_night_crime_location = crimes_10pm_to_4am.value_counts("AREA NAME").idxmax()
peak_night_crime_location
'Central'
crimes_10pm_to_4am.value_counts("AREA NAME").max()
4211

Task 3

Identify the number of crimes committed against victims by age group (0-18, 18-25, 26-34, 35-44, 45-54, 55-64, 65+). Save as a pandas Series called victim_ages

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

# Create a new column based on the age bins
crimes['Age Group'] = pd.cut(crimes['Vict Age'], bins=age_bins, labels=age_labels)
crimes.head(10)

DR_NO

Date Rptd

DATE OCC

TIME OCC

AREA NAME

Crm Cd Desc

Vict Age

Vict Sex

Vict Descent

Weapon Desc

Status Desc

LOCATION

TimeOcc_int

Age Group

0

221412410

2022-06-15

2020-11-12

1700

Pacific

THEFT FROM MOTOR VEHICLE - PETTY ($950 & UNDER)

0

NaN

NaN

NaN

Invest Cont

13600 MARINA POINT DR

1700

NaN

1

220314085

2022-07-22

2020-05-12

1110

Southwest

THEFT OF IDENTITY

27

F

B

NaN

Invest Cont

2500 S SYCAMORE AV

1110

26-34

2

222013040

2022-08-06

2020-06-04

1620

Olympic

THEFT OF IDENTITY

60

M

H

NaN

Invest Cont

3300 SAN MARINO ST

1620

55-64

3

220614831

2022-08-18

2020-08-17

1200

Hollywood

THEFT OF IDENTITY

28

M

H

NaN

Invest Cont

1900 TRANSIENT

1200

26-34

4

231207725

2023-02-27

2020-01-27

0635

77th Street

THEFT OF IDENTITY

37

M

H

NaN

Invest Cont

6200 4TH AV

635

35-44

5

220213256

2022-07-14

2020-07-14

0900

Rampart

THEFT OF IDENTITY

79

M

B

NaN

Invest Cont

1200 W 7TH ST

900

65+

6

221216052

2022-07-07

2020-02-23

1000

77th Street

THEFT OF IDENTITY

28

F

B

NaN

Invest Cont

500 W 75TH ST

1000

26-34

7

221515929

2022-10-10

2020-04-01

1200

N Hollywood

THEFT OF IDENTITY

33

M

W

NaN

Invest Cont

5700 CARTWRIGHT AV

1200

26-34

8

231906599

2023-03-03

2020-01-14

1335

Mission

THEFT OF IDENTITY

35

M

O

NaN

Invest Cont

14500 WILLOWGREEN LN

1335

35-44

9

231207476

2023-02-27

2020-08-15

0001

77th Street

BURGLARY

72

M

B

NaN

Invest Cont

8800 HAAS AV

1

65+

victim_ages = crimes.value_counts("Age Group")
victim_ages
Age Group
26-34    47470
35-44    42157
45-54    28353
18-25    28291
55-64    20169
65+      14747
0-18      4528
dtype: int64

DataCamp codes

# Import required libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# Read in and preview the dataset
crimes = pd.read_csv("crimes.csv", parse_dates=["Date Rptd", "DATE OCC"], dtype={"TIME OCC": str})
crimes.head()

## Which hour has the highest frequency of crimes? Store as an integer variable called peak_crime_hour

# Extract the first two digits from "TIME OCC", representing the hour,
# and convert to integer data type
crimes["HOUR OCC"] = crimes["TIME OCC"].str[:2].astype(int)

# Preview the DataFrame to confirm the new column is correct
crimes.head()

# Produce a countplot to find the largest frequency of crimes by hour
sns.countplot(data=crimes, x="HOUR OCC")
plt.show()

# Midday has the largest volume of crime
peak_crime_hour = 12

## Which area has the largest frequency of night crimes (crimes committed between 10pm and 3:59am)? 
## Save as a string variable called peak_night_crime_location
# Filter for the night-time hours
# 0 = midnight; 3 = crimes between 3am and 3:59am, i.e., don't include 4
night_time = crimes[crimes["HOUR OCC"].isin([22,23,0,1,2,3])]

# Group by "AREA NAME" and count occurrences, filtering for the largest value and saving the "AREA NAME"
peak_night_crime_location = night_time.groupby("AREA NAME", 
                                               as_index=False)["HOUR OCC"].count().sort_values("HOUR OCC",
                                                                                               ascending=False).iloc[0]["AREA NAME"]
# Print the peak night crime location
print(f"The area with the largest volume of night crime is {peak_night_crime_location}")

## Identify the number of crimes committed against victims by age group (0-18, 18-25, 26-34, 35-44, 45-54, 55-64, 65+) 
## Save as a pandas Series called victim_ages
# Create bins and labels for victim age ranges
age_bins = [0, 17, 25, 34, 44, 54, 64, np.inf]
age_labels = ["0-18", "18-25", "26-34", "35-44", "45-54", "55-64", "65+"]

# Add a new column using pd.cut() to bin values into discrete intervals
crimes["Age Bracket"] = pd.cut(crimes["Vict Age"],
                               bins=age_bins,
                               labels=age_labels)

# Find the category with the largest frequency
victim_ages = crimes["Age Bracket"].value_counts()
print(victim_ages)