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