File size: 16,262 Bytes
bc413e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "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"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "6abd0a8c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "import zipfile\n",
    "import pandas as pd\n",
    "from io import BytesIO\n",
    "\n",
    "# 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": "code",
   "execution_count": 76,
   "id": "c7195730",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from pyproj import Transformer\n",
    "\n",
    "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",
    "    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",
    "    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",
    "    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",
    "    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",
    "        \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",
    "\n",
    "        \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\")\n"
   ]
  },
  {
   "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": "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
}