Upload Cleaned Data Processing.ipynb
Browse files- Cleaned Data Processing.ipynb +411 -0
Cleaned Data Processing.ipynb
ADDED
@@ -0,0 +1,411 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "markdown",
|
5 |
+
"id": "03bc9776",
|
6 |
+
"metadata": {},
|
7 |
+
"source": [
|
8 |
+
"# RTP Crime Data Processing Code \n",
|
9 |
+
"## - Supplementary Note to HuggingFace Dataset: zwn22/NC_Crime"
|
10 |
+
]
|
11 |
+
},
|
12 |
+
{
|
13 |
+
"cell_type": "markdown",
|
14 |
+
"id": "e6d8ff40",
|
15 |
+
"metadata": {},
|
16 |
+
"source": [
|
17 |
+
"## Abstract"
|
18 |
+
]
|
19 |
+
},
|
20 |
+
{
|
21 |
+
"cell_type": "markdown",
|
22 |
+
"id": "75ab08c8",
|
23 |
+
"metadata": {},
|
24 |
+
"source": [
|
25 |
+
"The dataset is compiled from public police incident reports from multiple cities within North Carolina's Research Triangle Park (RTP), encompassing the years 2015 to 2024. Sourced from the open data portals of Cary, Chapel Hill, Durham, and Raleigh, the dataset was meticulously merged and cleaned to remove any incomplete entries. The dataset underwent a process of merging data from these cities, followed by cleaning to remove incomplete rows. Additionally, the dataset focuses on extracting and categorizing major crime types, providing valuable information such as crime type, time, location of occurrence, and other relevant details.\n",
|
26 |
+
"\n",
|
27 |
+
"Since each raw dataset has a different size and column naming convention, it is **NOT FEASIBLE** to simplify the entire cleanup process in a single Python (.py) file. Therefore, a Jupyter notebook is provided for anyone interested in delving into the intricacies of how the unified dataset was crafted. This is a lite version and does not include the Exploratory Data Analysis (EDA) section. For those interested in the EDA aspect, another Jupyter notebook titled `EDA.ipynb` is available for further exploration."
|
28 |
+
]
|
29 |
+
},
|
30 |
+
{
|
31 |
+
"cell_type": "markdown",
|
32 |
+
"id": "6ac2348b",
|
33 |
+
"metadata": {},
|
34 |
+
"source": [
|
35 |
+
"## Code"
|
36 |
+
]
|
37 |
+
},
|
38 |
+
{
|
39 |
+
"cell_type": "markdown",
|
40 |
+
"id": "54f59d24",
|
41 |
+
"metadata": {},
|
42 |
+
"source": [
|
43 |
+
"First, import the required packages."
|
44 |
+
]
|
45 |
+
},
|
46 |
+
{
|
47 |
+
"cell_type": "code",
|
48 |
+
"execution_count": 2,
|
49 |
+
"id": "711a0e17",
|
50 |
+
"metadata": {},
|
51 |
+
"outputs": [],
|
52 |
+
"source": [
|
53 |
+
"import pandas as pd\n",
|
54 |
+
"import requests\n",
|
55 |
+
"import zipfile\n",
|
56 |
+
"import pandas as pd\n",
|
57 |
+
"from io import BytesIO\n",
|
58 |
+
"from pyproj import Transformer"
|
59 |
+
]
|
60 |
+
},
|
61 |
+
{
|
62 |
+
"cell_type": "markdown",
|
63 |
+
"id": "ee8ca88e",
|
64 |
+
"metadata": {},
|
65 |
+
"source": [
|
66 |
+
"The script below simplifies the process of obtaining and preparing crime data from various sources for analysis. Functions were defined to download and extract CSV files from ZIP archives and to download and read XLSX files from specified URLs. These functions were used to retrieve crime data from four different locations: Chapel Hill, Raleigh, Cary and Durham, each of which was accessed via its own unique URL. \\\n",
|
67 |
+
"Utilizing URLs to access the data ensures that the analysis is always based on the most current and accurate information, thereby eliminating the discrepancies that can occur when using locally stored files. By ensuring that the data are correctly formatted into pandas data frames, this approach not only simplifies the initial data collection and preparation steps, but also improves the reliability of the analysis and provides the basis for a comprehensive understanding of the dynamics of crime at these locations. In addition, the Cary and Durham government websites provide direct download links for easy access to the data. However, the Raleigh and Chapel Hill government websites impose restrictions on direct access to the data, so these datasets must be downloaded manually and then uploaded to a dedicated HuggingFace channel to ensure availability."
|
68 |
+
]
|
69 |
+
},
|
70 |
+
{
|
71 |
+
"cell_type": "code",
|
72 |
+
"execution_count": 8,
|
73 |
+
"id": "6abd0a8c",
|
74 |
+
"metadata": {},
|
75 |
+
"outputs": [],
|
76 |
+
"source": [
|
77 |
+
"# Function to handle ZIP files containing CSVs\n",
|
78 |
+
"def download_and_read_zip_csv(url):\n",
|
79 |
+
" with requests.get(url) as response:\n",
|
80 |
+
" response.raise_for_status() \n",
|
81 |
+
" with zipfile.ZipFile(BytesIO(response.content)) as zip_file:\n",
|
82 |
+
" data_file_name = zip_file.namelist()[0] \n",
|
83 |
+
" with zip_file.open(data_file_name) as df:\n",
|
84 |
+
" data = pd.read_csv(df, low_memory=False)\n",
|
85 |
+
" return data\n",
|
86 |
+
"\n",
|
87 |
+
"# Function to download and read an XLSX file\n",
|
88 |
+
"def download_and_read_xlsx(url):\n",
|
89 |
+
" with requests.get(url) as response:\n",
|
90 |
+
" response.raise_for_status()\n",
|
91 |
+
" data = pd.read_excel(BytesIO(response.content))\n",
|
92 |
+
" return data\n",
|
93 |
+
"\n",
|
94 |
+
"# URLs\n",
|
95 |
+
"url_chapel = \"https://huggingface.co/datasets/zwn22/NC_Crime/resolve/main/Chapel_Hill.csv.zip\"\n",
|
96 |
+
"url_raleigh = \"https://huggingface.co/datasets/zwn22/NC_Crime/resolve/main/Raleigh.csv.zip\"\n",
|
97 |
+
"url_cary = \"https://data.townofcary.org/api/explore/v2.1/catalog/datasets/cpd-incidents/exports/csv?lang=en&timezone=US%2FEastern&use_labels=true&delimiter=%2C\"\n",
|
98 |
+
"url_durham = \"https://www.arcgis.com/sharing/rest/content/items/7132216432df4957830593359b0c4030/data\"\n",
|
99 |
+
"\n",
|
100 |
+
"Chapel = download_and_read_zip_csv(url_chapel)\n",
|
101 |
+
"Raleigh = download_and_read_zip_csv(url_raleigh)\n",
|
102 |
+
"Cary = pd.read_csv(url_cary, low_memory=False) \n",
|
103 |
+
"Durham = download_and_read_xlsx(url_durham) "
|
104 |
+
]
|
105 |
+
},
|
106 |
+
{
|
107 |
+
"cell_type": "markdown",
|
108 |
+
"id": "a26d2f40",
|
109 |
+
"metadata": {},
|
110 |
+
"source": [
|
111 |
+
"Following the initial data collection phase, the code below further refined the crime analysis process by categorizing, cleaning, and geospatially aligning crime data from Cary, Chapel Hill, Durham, and Raleigh. Utilizing ChatGPT's advanced NLP capabilities to develop a complex crime category mapping system, the methodology surpasses traditional methods in accuracy and depth. **Validated by course instructor Dr. Huang**, this innovative mapping ensures that each crime is accurately classified into categories such as theft, assault, and drug-related crimes.\\\n",
|
112 |
+
"This step is crucial for transforming raw data into a structured format for detailed and nuanced crime analysis. By systematically categorizing crimes and transforming geographic coordinates to ensure accuracy, the script prepares the dataset for in-depth analysis, reflecting the latest trends and patterns of crime in those cities."
|
113 |
+
]
|
114 |
+
},
|
115 |
+
{
|
116 |
+
"cell_type": "code",
|
117 |
+
"execution_count": 76,
|
118 |
+
"id": "c7195730",
|
119 |
+
"metadata": {},
|
120 |
+
"outputs": [],
|
121 |
+
"source": [
|
122 |
+
"def process_crime_data(filename, city_name):\n",
|
123 |
+
" pd.options.mode.chained_assignment = None \n",
|
124 |
+
"\n",
|
125 |
+
" def categorize_crime(crime):\n",
|
126 |
+
" for category, crimes in crime_mapping.items():\n",
|
127 |
+
" if crime in crimes:\n",
|
128 |
+
" return category\n",
|
129 |
+
" return 'Miscellaneous'\n",
|
130 |
+
" \n",
|
131 |
+
" # For the Durham raw dataset, which provides state plane coordinates rather than direct geographic coordinates,\n",
|
132 |
+
" # a specific transformation process is required to convert these to latitude and longitude values \n",
|
133 |
+
" # for mapping and analysis. The provided function convert_coordinates utilizes the Transformer class \n",
|
134 |
+
" # from the pyproj library to perform this conversion. The function is designed to take X and Y coordinates \n",
|
135 |
+
" # in the North Carolina State Plane (NAD83), identified by the EPSG code 2264, and transform them into \n",
|
136 |
+
" # geographic coordinates (latitude and longitude) in the WGS 84 coordinate system, which is universally \n",
|
137 |
+
" # used for global positioning (identified by the EPSG code 4326).\n",
|
138 |
+
"\n",
|
139 |
+
" def convert_coordinates(x, y):\n",
|
140 |
+
" transformer = Transformer.from_crs(\"epsg:2264\", \"epsg:4326\", always_xy=True)\n",
|
141 |
+
" lon, lat = transformer.transform(x, y)\n",
|
142 |
+
" return pd.Series([lat, lon])\n",
|
143 |
+
" \n",
|
144 |
+
" # Provided by ChatGPT (proved by Dr.Huang)\n",
|
145 |
+
" crime_mapping = {\n",
|
146 |
+
" 'Theft': [\n",
|
147 |
+
" 'BURGLARY', 'MOTOR VEHICLE THEFT', 'LARCENY',\n",
|
148 |
+
" 'LARCENY - AUTOMOBILE PARTS OR ACCESSORIES', 'TOWED/ABANDONED VEHICLE',\n",
|
149 |
+
" 'LARCENY - FROM MOTOR VEHICLE', 'LARCENY - SHOPLIFTING', 'LOST PROPERTY',\n",
|
150 |
+
" 'VANDALISM', 'LARCENY - ALL OTHER', 'LARCENY - FROM BUILDING',\n",
|
151 |
+
" 'RECOVERED STOLEN PROPERTY (OTHER JURISDICTION)', 'LARCENY - POCKET-PICKING',\n",
|
152 |
+
" 'LARCENY - FROM COIN-OPERATED DEVICE', 'LARCENY - PURSESNATCHING',\n",
|
153 |
+
" 'LARCENY FROM MV', 'MV THEFT', 'STOLEN PROPERTY',\n",
|
154 |
+
" 'THEFT/LARCENY', 'LARCENY FROM AU', 'LARCENY FROM PE', 'LARCENY OF OTHE',\n",
|
155 |
+
" 'LARCENY FROM BU', 'LARCENY OF BIKE', 'LARCENY FROM RE', 'LARCENY OF AUTO'\n",
|
156 |
+
" ],\n",
|
157 |
+
" 'Fraud': [\n",
|
158 |
+
" 'FRAUD-IDENTITY THEFT', 'EMBEZZLEMENT', 'COUNTERFEITING/FORGERY',\n",
|
159 |
+
" 'FRAUD - CONFIDENCE GAMES/TRICKERY', 'FRAUD - CREDIT CARD/ATM',\n",
|
160 |
+
" 'FRAUD - UNAUTHORIZED USE OF CONVEYANCE', 'FRAUD - FALSE PRETENSE',\n",
|
161 |
+
" 'FRAUD - IMPERSONATION', 'FRAUD - WIRE/COMPUTER/OTHER ELECTRONIC',\n",
|
162 |
+
" 'FRAUD - WORTHLESS CHECKS', 'FRAUD-FAIL TO RETURN RENTAL VEHICLE',\n",
|
163 |
+
" 'FRAUD-HACKING/COMPUTER INVASION', 'FRAUD-WELFARE FRAUD', 'FRAUD', 'BRIBERY',\n",
|
164 |
+
" 'FRAUD OR DECEPT'\n",
|
165 |
+
" ],\n",
|
166 |
+
" 'Assault': [\n",
|
167 |
+
" 'SIMPLE ASSAULT', 'AGGRAVATED ASSAULT', 'ASSAULT', 'ASSAULT/SEXUAL',\n",
|
168 |
+
" 'STAB GUNSHOT PE', 'ACTIVE ASSAILAN'\n",
|
169 |
+
" ],\n",
|
170 |
+
" 'Drugs': [\n",
|
171 |
+
" 'DRUG/NARCOTIC VIOLATIONS', 'DRUG EQUIPMENT/PARAPHERNALIA', 'DRUGS',\n",
|
172 |
+
" 'DRUG VIOLATIONS'\n",
|
173 |
+
" ],\n",
|
174 |
+
" 'Sexual Offenses': [\n",
|
175 |
+
" 'SEX OFFENSE - FORCIBLE RAPE', 'SEX OFFENSE - SEXUAL ASSAULT WITH AN OBJECT',\n",
|
176 |
+
" 'SEX OFFENSE - FONDLING', 'SEX OFFENSE - INDECENT EXPOSURE', 'SEX OFFENSE - FORCIBLE SODOMY',\n",
|
177 |
+
" 'SEX OFFENSE - STATUTORY RAPE', 'SEX OFFENSE - PEEPING TOM', 'SEX OFFENSE - INCEST',\n",
|
178 |
+
" 'SEX OFFENSES', 'SEXUAL OFFENSE'\n",
|
179 |
+
" ],\n",
|
180 |
+
" 'Homicide': [\n",
|
181 |
+
" 'HOMICIDE-MURDER/NON-NEGLIGENT MANSLAUGHTER', 'JUSTIFIABLE HOMICIDE',\n",
|
182 |
+
" 'HOMICIDE - NEGLIGENT MANSLAUGHTER', 'MURDER', 'SUICIDE ATTEMPT', 'ABUSE/ABANDOMEN',\n",
|
183 |
+
" 'DECEASED PERSON'\n",
|
184 |
+
" ],\n",
|
185 |
+
" 'Arson': ['ARSON'],\n",
|
186 |
+
" 'Kidnapping': ['KIDNAPPING/ABDUCTION', 'KIDNAPPING'],\n",
|
187 |
+
" 'Weapons Violations': ['WEAPON VIOLATIONS', 'WEAPONS VIOLATION', 'WEAPON/FIREARMS'],\n",
|
188 |
+
" 'Traffic Violations': [\n",
|
189 |
+
" 'ALL TRAFFIC (EXCEPT DWI)', 'TRAFFIC', 'UNAUTHORIZED MOTOR VEHICLE USE',\n",
|
190 |
+
" 'TRAFFIC VIOLATIONS', 'LIQUOR LAW VIOLATIONS', 'TRAFFIC STOP', 'TRAFFIC/TRANSPO',\n",
|
191 |
+
" 'TRAFFIC VIOLATI', 'MVC', 'MVC W INJURY', 'MVC W INJURY AB', 'MVC W INJURY DE',\n",
|
192 |
+
" 'MVC ENTRAPMENT'\n",
|
193 |
+
" ],\n",
|
194 |
+
" 'Disorderly Conduct': [\n",
|
195 |
+
" 'DISORDERLY CONDUCT', 'DISORDERLY CONDUCT-DRUNK AND DISRUPTIVE',\n",
|
196 |
+
" 'DISORDERLY CONDUCT-FIGHTING (AFFRAY)', 'DISORDERLY CONDUCT-UNLAWFUL ASSEMBLY',\n",
|
197 |
+
" 'DISTURBANCE/NUI', 'DOMESTIC DISTUR', 'DISPUTE', 'DISTURBANCE', 'LOST PROPERTY',\n",
|
198 |
+
" 'TRESPASSING/UNW', 'REFUSAL TO LEAV', 'SUSPICIOUS COND', 'STRUCTURE FIRE'\n",
|
199 |
+
" ],\n",
|
200 |
+
" 'Gambling': [\n",
|
201 |
+
" 'GAMBLING - OPERATING/PROMOTING/ASSISTING', 'GAMBLING - BETTING/WAGERING', 'GAMBLING'\n",
|
202 |
+
" ],\n",
|
203 |
+
" 'Animal-related Offenses': ['ANIMAL CRUELTY', 'ANIMAL BITE', 'ANIMAL', 'ANIMAL CALL'],\n",
|
204 |
+
" 'Prostitution-related Offenses': [\n",
|
205 |
+
" 'PROSTITUTION', 'PROSTITUTION - ASSISTING/PROMOTING', 'PROSTITUTION - PURCHASING'\n",
|
206 |
+
" ],\n",
|
207 |
+
" 'Miscellaneous': [\n",
|
208 |
+
" 'MISCELLANEOUS', 'ALL OTHER OFFENSES', '<Null>', 'SUSPICIOUS/WANT', 'MISC OFFICER IN',\n",
|
209 |
+
" 'INDECENCY/LEWDN', 'PUBLIC SERVICE', 'TRESPASSING', 'UNKNOWN PROBLEM', 'LOUD NOISE',\n",
|
210 |
+
" 'ESCORT', 'ABDUCTION/CUSTO', 'THREATS', 'BURGLAR ALARM', 'DOMESTIC', 'PROPERTY FOUND',\n",
|
211 |
+
" 'FIREWORKS', 'MISSING/RUNAWAY', 'MENTAL DISORDER', 'CHECK WELL BEIN', 'PSYCHIATRIC',\n",
|
212 |
+
" 'OPEN DOOR', 'ABANDONED AUTO', 'HARASSMENT THRE', 'JUVENILE RELATE', 'ASSIST MOTORIST',\n",
|
213 |
+
" 'HAZARDOUS DRIVI', 'GAS LEAK FIRE', 'ASSIST OTHER AG', 'DOMESTIC ASSIST', 'SUSPICIOUS VEHI',\n",
|
214 |
+
" 'UNKNOWN LE', 'ALARMS', '911 HANGUP', 'BOMB/CBRN/PRODU', 'STATIONARY PATR', 'LITTERING',\n",
|
215 |
+
" 'HOUSE CHECK', 'CARDIAC', 'CLOSE PATROL', 'BOMB FOUND/SUSP', 'INFO FOR ALL UN', 'UNCONCIOUS OR F',\n",
|
216 |
+
" 'LIFTING ASSISTA', 'ATTEMPT TO LOCA', 'SICK PERSON', 'HEAT OR COLD EX', 'CONFINED SPACE',\n",
|
217 |
+
" 'TRAUMATIC INJUR', 'DROWNING', 'CITY ORDINANCE', 'JUVENILE', 'MISSING PERSON',\n",
|
218 |
+
" 'PUBLIC SERVICE', 'PUBLICE SERVICE'\n",
|
219 |
+
" ],\n",
|
220 |
+
" 'Robbery': ['ROBBERY'],\n",
|
221 |
+
" 'Extortion': ['EXTORTION'],\n",
|
222 |
+
" 'Human Trafficking': ['HUMAN TRAFFICKING']\n",
|
223 |
+
" }\n",
|
224 |
+
" \n",
|
225 |
+
" # Provided by ChatGPT (proved by Dr.Huang)\n",
|
226 |
+
" crime_severity_mapping = {\n",
|
227 |
+
" 'Miscellaneous': 'Minor',\n",
|
228 |
+
" 'Disorderly Conduct': 'Minor',\n",
|
229 |
+
" 'Traffic Violations': 'Minor',\n",
|
230 |
+
" 'Animal-related Offenses': 'Minor',\n",
|
231 |
+
" 'Prostitution-related Offenses': 'Minor',\n",
|
232 |
+
" 'Gambling': 'Minor',\n",
|
233 |
+
" 'Public Service': 'Minor',\n",
|
234 |
+
" 'Juvenile': 'Minor',\n",
|
235 |
+
" 'Fraud': 'Moderate',\n",
|
236 |
+
" 'Theft': 'Moderate',\n",
|
237 |
+
" 'Drugs': 'Moderate',\n",
|
238 |
+
" 'Assault': 'Moderate',\n",
|
239 |
+
" 'Sexual Offenses': 'Moderate',\n",
|
240 |
+
" 'Weapons Violations': 'Moderate',\n",
|
241 |
+
" 'Vandalism': 'Moderate',\n",
|
242 |
+
" 'Burglary': 'Moderate',\n",
|
243 |
+
" 'Robbery': 'Moderate',\n",
|
244 |
+
" 'Kidnapping': 'Severe',\n",
|
245 |
+
" 'Homicide': 'Severe',\n",
|
246 |
+
" 'Arson': 'Severe',\n",
|
247 |
+
" 'Extortion': 'Severe',\n",
|
248 |
+
" 'Human Trafficking': 'Severe',\n",
|
249 |
+
" 'Murder': 'Severe'\n",
|
250 |
+
" }\n",
|
251 |
+
"\n",
|
252 |
+
" df = pd.DataFrame() # Initialize an empty DataFrame for generic use\n",
|
253 |
+
" \n",
|
254 |
+
" \n",
|
255 |
+
" \n",
|
256 |
+
" # Due to the uniqueness of the datasets, each dataset requires customized functionality to handle the\n",
|
257 |
+
" if city_name == 'Durham':\n",
|
258 |
+
" df = pd.read_excel(filename)\n",
|
259 |
+
" df['Weapon'] = df['Weapon'].replace(['(blank)', 'Not Applicable/None', 'Unknown/Not Stated'], None) \n",
|
260 |
+
" df['crime_major_category'] = df['Offense'].apply(categorize_crime)\n",
|
261 |
+
" # Apply coordinate conversion and categorization\n",
|
262 |
+
" coordinates = df.apply(lambda row: convert_coordinates(row['X'], row['Y']), axis=1)\n",
|
263 |
+
" df['latitude'], df['longitude'] = coordinates[0], coordinates[1]\n",
|
264 |
+
"\n",
|
265 |
+
" new_df = pd.DataFrame({\n",
|
266 |
+
" \"year\": pd.to_datetime(df['Report Date']).dt.year,\n",
|
267 |
+
" \"city\": \"Durham\",\n",
|
268 |
+
" \"crime_major_category\": df['crime_major_category'],\n",
|
269 |
+
" \"crime_detail\": df['Offense'].str.title(),\n",
|
270 |
+
" \"latitude\": df['latitude'],\n",
|
271 |
+
" \"longitude\": df['longitude'],\n",
|
272 |
+
" \"occurance_time\": pd.to_datetime(df['Report Date'].astype(str) + ' ' + df['Report Time'], errors='coerce').dt.strftime('%Y/%m/%d %H:%M:%S'),\n",
|
273 |
+
" \"clear_status\": df['Status'],\n",
|
274 |
+
" \"incident_address\": df['Address'],\n",
|
275 |
+
" \"notes\": df['Weapon'].apply(lambda x: f\"Weapon: {x}\" if pd.notnull(x) else \"No Data\")\n",
|
276 |
+
" }).fillna(\"No Data\") \n",
|
277 |
+
" elif city_name == 'Raleigh':\n",
|
278 |
+
" df = pd.read_csv(filename, low_memory=False)\n",
|
279 |
+
" new_df = pd.DataFrame({\n",
|
280 |
+
" \"year\": df['reported_year'],\n",
|
281 |
+
" \"city\": \"Raleigh\",\n",
|
282 |
+
" \"crime_major_category\": df['crime_category'].apply(categorize_crime),\n",
|
283 |
+
" \"crime_detail\": df['crime_description'],\n",
|
284 |
+
" \"latitude\": df['latitude'].round(5).fillna(0),\n",
|
285 |
+
" \"longitude\": df['longitude'].round(5).fillna(0),\n",
|
286 |
+
" \"occurance_time\": pd.to_datetime(df['reported_date'].str.replace(r'\\+\\d{2}$', '', regex=True), errors='coerce').dt.strftime('%Y/%m/%d %H:%M:%S'),\n",
|
287 |
+
" \"clear_status\": None,\n",
|
288 |
+
" \"incident_address\": df['reported_block_address'] + ', ' + df['district'] + ', Raleigh',\n",
|
289 |
+
" \"notes\": 'District: '+ df['district'].str.title()\n",
|
290 |
+
" }).fillna(\"No Data\")\n",
|
291 |
+
" \n",
|
292 |
+
" elif city_name == 'Cary':\n",
|
293 |
+
" df = pd.read_csv(filename, low_memory=False).dropna(subset=['Year'])\n",
|
294 |
+
" new_df = pd.DataFrame({\n",
|
295 |
+
" \"year\": df[\"Year\"].astype(int),\n",
|
296 |
+
" \"city\": \"Cary\",\n",
|
297 |
+
" \"crime_major_category\": df['Crime Category'].apply(categorize_crime).str.title(),\n",
|
298 |
+
" \"crime_detail\": df['Crime Type'].str.title(),\n",
|
299 |
+
" \"latitude\": df['Lat'].fillna(0).round(5).fillna(0),\n",
|
300 |
+
" \"longitude\": df['Lon'].fillna(0).round(5).fillna(0),\n",
|
301 |
+
" \"occurance_time\": pd.to_datetime(df['Begin Date Of Occurrence'] + ' ' + df['Begin Time Of Occurrence']).dt.strftime('%Y/%m/%d %H:%M:%S'),\n",
|
302 |
+
" \"clear_status\": None,\n",
|
303 |
+
" \"incident_address\": df['Geo Code'],\n",
|
304 |
+
" \"notes\": 'District: '+ df['District'].str.title() + ' Violent Property: ' + df['Violent Property'].str.title()\n",
|
305 |
+
" }).fillna(\"No Data\")\n",
|
306 |
+
" \n",
|
307 |
+
" elif city_name == 'Chapel Hill':\n",
|
308 |
+
" df = pd.read_csv(filename, low_memory=False)\n",
|
309 |
+
" replace_values = {'<Null>': None, 'NONE': None}\n",
|
310 |
+
" df['Weapon_Description'] = df['Weapon_Description'].replace(replace_values)\n",
|
311 |
+
" new_df = pd.DataFrame({\n",
|
312 |
+
" \"year\": pd.to_datetime(df['Date_of_Occurrence']).dt.year,\n",
|
313 |
+
" \"city\": \"Chapel Hill\",\n",
|
314 |
+
" \"crime_major_category\": df['Reported_As'].apply(categorize_crime),\n",
|
315 |
+
" \"crime_detail\": df['Offense'].str.title(),\n",
|
316 |
+
" \"latitude\": df['X'].round(5).fillna(0),\n",
|
317 |
+
" \"longitude\": df['Y'].round(5).fillna(0),\n",
|
318 |
+
" \"occurance_time\": pd.to_datetime(df['Date_of_Occurrence'].str.replace(r'\\+\\d{2}$', '', regex=True)).dt.strftime('%Y/%m/%d %H:%M:%S'),\n",
|
319 |
+
" \"clear_status\": None,\n",
|
320 |
+
" \"incident_address\": df['Street'].str.replace(\"@\", \" \"),\n",
|
321 |
+
" \"notes\": df['Weapon_Description'].apply(lambda x: f\"Weapon: {x}\" if pd.notnull(x) else \"Weapon: None\").str.title()\n",
|
322 |
+
" }).fillna(\"No Data\")\n",
|
323 |
+
" indices_to_switch = new_df.loc[(new_df['latitude'].between(-82, -75)) & (new_df['longitude'].between(35, 40))].index\n",
|
324 |
+
" for idx in indices_to_switch:\n",
|
325 |
+
" new_df.at[idx, 'latitude'], new_df.at[idx, 'longitude'] = new_df.at[idx, 'longitude'], new_df.at[idx, 'latitude']\n",
|
326 |
+
"\n",
|
327 |
+
" \n",
|
328 |
+
" new_df = new_df[new_df['year'] >= 2015]\n",
|
329 |
+
" new_df = new_df.loc[(new_df['latitude'].between(35, 40)) & (new_df['longitude'].between(-82, -75))]\n",
|
330 |
+
" new_df['crime_severity'] = new_df['crime_major_category'].map(crime_severity_mapping)\n",
|
331 |
+
" return new_df\n",
|
332 |
+
"\n",
|
333 |
+
"# Example usage\n",
|
334 |
+
"Cary_new = process_crime_data(\"Cary.csv\", \"Cary\")\n",
|
335 |
+
"Chapel_new = process_crime_data(\"Chapel_hill.csv\", \"Chapel Hill\")\n",
|
336 |
+
"Durham_new = process_crime_data(\"Durham.xlsx\", \"Durham\")\n",
|
337 |
+
"Raleigh_new = process_crime_data(\"Raleigh.csv\", \"Raleigh\")"
|
338 |
+
]
|
339 |
+
},
|
340 |
+
{
|
341 |
+
"cell_type": "markdown",
|
342 |
+
"id": "60238483",
|
343 |
+
"metadata": {},
|
344 |
+
"source": [
|
345 |
+
"Finally, the four processed datasets are merged, saved to a local file, and uploaded to GitHub for easy remote access."
|
346 |
+
]
|
347 |
+
},
|
348 |
+
{
|
349 |
+
"cell_type": "code",
|
350 |
+
"execution_count": 77,
|
351 |
+
"id": "cfd5d140",
|
352 |
+
"metadata": {},
|
353 |
+
"outputs": [],
|
354 |
+
"source": [
|
355 |
+
"NC_v1 = pd.concat([Durham_new, Chapel_new, Cary_new, Raleigh_new], ignore_index=True)\n",
|
356 |
+
"NC_v1.to_csv('NC_v1.csv', index=False)"
|
357 |
+
]
|
358 |
+
},
|
359 |
+
{
|
360 |
+
"cell_type": "markdown",
|
361 |
+
"id": "5793cab6",
|
362 |
+
"metadata": {},
|
363 |
+
"source": [
|
364 |
+
"The shape of the final dataset is given below:"
|
365 |
+
]
|
366 |
+
},
|
367 |
+
{
|
368 |
+
"cell_type": "code",
|
369 |
+
"execution_count": 5,
|
370 |
+
"id": "8186c46a",
|
371 |
+
"metadata": {},
|
372 |
+
"outputs": [
|
373 |
+
{
|
374 |
+
"data": {
|
375 |
+
"text/plain": [
|
376 |
+
"(585886, 11)"
|
377 |
+
]
|
378 |
+
},
|
379 |
+
"execution_count": 5,
|
380 |
+
"metadata": {},
|
381 |
+
"output_type": "execute_result"
|
382 |
+
}
|
383 |
+
],
|
384 |
+
"source": [
|
385 |
+
"NC_v1 = pd.read_csv(\"NC_v1.csv\")\n",
|
386 |
+
"NC_v1.shape"
|
387 |
+
]
|
388 |
+
}
|
389 |
+
],
|
390 |
+
"metadata": {
|
391 |
+
"kernelspec": {
|
392 |
+
"display_name": "Python 3 (ipykernel)",
|
393 |
+
"language": "python",
|
394 |
+
"name": "python3"
|
395 |
+
},
|
396 |
+
"language_info": {
|
397 |
+
"codemirror_mode": {
|
398 |
+
"name": "ipython",
|
399 |
+
"version": 3
|
400 |
+
},
|
401 |
+
"file_extension": ".py",
|
402 |
+
"mimetype": "text/x-python",
|
403 |
+
"name": "python",
|
404 |
+
"nbconvert_exporter": "python",
|
405 |
+
"pygments_lexer": "ipython3",
|
406 |
+
"version": "3.11.5"
|
407 |
+
}
|
408 |
+
},
|
409 |
+
"nbformat": 4,
|
410 |
+
"nbformat_minor": 5
|
411 |
+
}
|