{ "cells": [ { "cell_type": "markdown", "id": "f50e09b6", "metadata": {}, "source": [ "# Introduction" ] }, { "cell_type": "markdown", "id": "ff929199", "metadata": {}, "source": [ "This is the EDA script for processing the huggingface dataset \"zwn22/NC_Crime\"." ] }, { "cell_type": "markdown", "id": "356beb0a", "metadata": {}, "source": [ "# Durham " ] }, { "cell_type": "markdown", "id": "f31470ef", "metadata": {}, "source": [ "NC State Plane ESPG: 2264 https://epsg.io/2264" ] }, { "cell_type": "code", "execution_count": 86, "id": "ae2c8d75", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "Durham = pd.read_excel('Durham.xlsx')" ] }, { "cell_type": "markdown", "id": "88a16949", "metadata": {}, "source": [ "## Exploratory Data Analysis" ] }, { "cell_type": "code", "execution_count": 87, "id": "857af355", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "Index(['Case Number', 'Report Date', 'Report Time', 'Status', 'Sequence',\n", " 'ATT/COM', 'UCR Code', 'Offense', 'Address', 'X', 'Y', 'District',\n", " 'Beat', 'Tract', 'Premise', 'Weapon'],\n", " dtype='object')" ] }, "execution_count": 87, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Durham.columns" ] }, { "cell_type": "code", "execution_count": 2, "id": "6059809c", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array(['(blank)', 'Not Applicable/None', 'Unknown/Not Stated',\n", " 'Personal Weapons', 'Knife/Cutting Instrument', 'Handgun',\n", " 'Blunt Objects', 'Rifle', 'Asphyxiation', 'Other Weapon',\n", " 'Narcotics/Drugs', 'Undetermined Firearm', 'Shotgun',\n", " 'Motor Vehicle/Vessel', 'Fire/Burning Tool/Device',\n", " 'Other Firearm', 'Explosives', 'Poison'], dtype=object)" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Durham['Weapon'].unique()" ] }, { "cell_type": "code", "execution_count": 3, "id": "e836498c", "metadata": {}, "outputs": [], "source": [ "Durham['Weapon'] = Durham['Weapon'].replace(['(blank)', 'Not Applicable/None', 'Unknown/Not Stated'], None)" ] }, { "cell_type": "code", "execution_count": 4, "id": "a484806d", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array(['INTIMIDATION', 'FRAUD-IDENTITY THEFT',\n", " 'LARCENY - AUTOMOBILE PARTS OR ACCESSORIES',\n", " 'TOWED/ABANDONED VEHICLE', 'DRUG/NARCOTIC VIOLATIONS',\n", " 'DRUG EQUIPMENT/PARAPHERNALIA', 'MOTOR VEHICLE THEFT', 'BURGLARY',\n", " 'SIMPLE ASSAULT', 'LARCENY - FROM MOTOR VEHICLE',\n", " 'LARCENY - SHOPLIFTING', 'LOST PROPERTY', 'VANDALISM',\n", " 'LARCENY - ALL OTHER', 'DV INFO REPORT (NO CRIME)',\n", " 'ALL OTHER CRIMINAL OFFENSES', 'LARCENY - FROM BUILDING',\n", " 'ALL OTHER OFFENSES-PAROLE/PROBATION VIOLATIONS', 'EMBEZZLEMENT',\n", " 'ASSIST OTHER AGENCY', 'AGGRAVATED ASSAULT',\n", " 'SEX OFFENSE - FORCIBLE RAPE',\n", " 'SEX OFFENSE - SEXUAL ASSAULT WITH AN OBJECT',\n", " 'COUNTERFEITING/FORGERY', 'FRAUD - CONFIDENCE GAMES/TRICKERY',\n", " 'SUSPICIOUS ACTIVITY', 'CALLS FOR SERVICE (NO CRIME)',\n", " 'ROBBERY - COMMERCIAL', 'ROBBERY - INDIVIDUAL',\n", " 'FRAUD - CREDIT CARD/ATM',\n", " 'FRAUD - UNAUTHORIZED USE OF CONVEYANCE', 'RUNAWAY',\n", " 'RECOVERED STOLEN PROPERTY (OTHER JURISDICTION)',\n", " 'ALL OTHER OFFENSES-COURT VIOLATIONS', 'DEATH INVESTIGATION',\n", " 'FRAUD - FALSE PRETENSE', 'SUICIDE', 'ALL TRAFFIC (EXCEPT DWI)',\n", " 'RECOVERED STOLEN VEHICLE (OTHER JURISDICTION)', 'TRESPASSING',\n", " 'FRAUD - IMPERSONATION', 'KIDNAPPING/ABDUCTION',\n", " 'WEAPON VIOLATIONS', 'ALL OTHER OFFENSES - HARASSING PHONE CALLS',\n", " 'FOUND PROPERTY', 'FRAUD - WIRE/COMPUTER/OTHER ELECTRONIC',\n", " 'FRAUD - WORTHLESS CHECKS', 'OFFENSE AGAINST FAMILY - OTHER',\n", " 'NON-CRIMINAL DETAINMENT (INVOLUNTARY COMMITMENT)',\n", " 'SEX OFFENSE - FONDLING', 'UNDISCIPLINED JUVENILE',\n", " 'LIQUOR LAW VIOLATIONS', 'BLACKMAIL/EXTORTION',\n", " 'DRIVING WHILE IMPAIRED', 'CRIME SCENE INVESTIGATION',\n", " 'MISSING PERSON', 'STOLEN PROPERTY',\n", " 'HOMICIDE-MURDER/NON-NEGLIGENT MANSLAUGHTER',\n", " 'DISORDERLY CONDUCT-DRUNK AND DISRUPTIVE',\n", " 'OFFENSES AGAINST FAMILY - CHILD ABUSE',\n", " 'ALL OTHER OFFENSES-ESCAPE FROM CUSTODY OR RESIST ARREST',\n", " 'CURFEW/LOITERING/VAGRANCY VIOLATIONS',\n", " 'SEX OFFENSE - FORCIBLE SODOMY',\n", " 'ALL OTHER OFFENSES-CITY ORDINANCE VIOLATIONS',\n", " 'PORNOGRAPHY/OBSCENE MATERIAL', 'ARSON', 'DISORDERLY CONDUCT',\n", " 'OFFENSES AGAINST FAMILY - NEGLECT',\n", " 'SEX OFFENSE - INDECENT EXPOSURE',\n", " 'DISORDERLY CONDUCT-FIGHTING (AFFRAY)', 'ROBBERY - BANK',\n", " 'LARCENY - POCKET-PICKING', 'LARCENY - FROM COIN-OPERATED DEVICE',\n", " 'FRAUD - WELFARE FRAUD', 'ANIMAL CRUELTY',\n", " 'SEX OFFENSE - STATUTORY RAPE', 'LARCENY - PURSESNATCHING',\n", " 'PROSTITUTION', 'FRAUD-FAIL TO RETURN RENTAL VEHICLE',\n", " 'OFFENSES AGAINST FAMILY - DESERTION/ABANDONMENT', 'BRIBERY',\n", " 'SEX OFFENSE - PEEPING TOM', 'JUSTIFIABLE HOMICIDE',\n", " 'FRAUD-HACKING/COMPUTER INVASION', 'TRUANCY',\n", " 'HUMAN TRAFFICKING/INVOLUNTARY SERVITUDE',\n", " 'HOMICIDE - NEGLIGENT MANSLAUGHTER',\n", " 'RESIST ARREST, ETC-REPEALED DO NOT USE',\n", " 'VANDALISM TO AUTO (NOT ACCIDENTAL)',\n", " 'DOMESTIC VIOLENCE ORDER VIOL-REPEALED DO NOT USE',\n", " 'GAMBLING - OPERATING/PROMOTING/ASSISTING',\n", " 'PROSTITUTION - ASSISTING/PROMOTING', 'SEX OFFENSE - INCEST',\n", " 'GAMBLING - BETTING/WAGERING', 'PROSTITUTION - PURCHASING',\n", " 'DISORDERLY CONDUCT-UNLAWFUL ASSEMBLY',\n", " 'HUMAN TRAFFICKING/COMMERCIAL SEX ACTS'], dtype=object)" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Durham['Offense'].unique()" ] }, { "cell_type": "code", "execution_count": 88, "id": "da37a48b", "metadata": {}, "outputs": [], "source": [ "from pyproj import Transformer\n", "\n", "def convert_coordinates(x, y):\n", "\n", " transformer = Transformer.from_crs(\"epsg:2264\", \"epsg:4326\", always_xy=True) # 注意设置always_xy=True以保持x,y顺序\n", "\n", " lon, lat = transformer.transform(x, y)\n", " \n", " return pd.Series([lat, lon])" ] }, { "cell_type": "code", "execution_count": 89, "id": "eed49097", "metadata": {}, "outputs": [], "source": [ "# Create a mapping dictionary for crime categories\n", "category_mapping = {\n", " 'Theft': ['LARCENY - AUTOMOBILE PARTS OR ACCESSORIES', 'TOWED/ABANDONED VEHICLE', 'MOTOR VEHICLE THEFT', 'BURGLARY', 'LARCENY - FROM MOTOR VEHICLE', 'LARCENY - SHOPLIFTING', 'LOST PROPERTY', 'VANDALISM', 'LARCENY - ALL OTHER', 'LARCENY - FROM BUILDING', 'RECOVERED STOLEN PROPERTY (OTHER JURISDICTION)', 'LARCENY - POCKET-PICKING', 'LARCENY - FROM COIN-OPERATED DEVICE', 'LARCENY - PURSESNATCHING'],\n", " 'Fraud': ['FRAUD-IDENTITY THEFT', 'EMBEZZLEMENT', 'COUNTERFEITING/FORGERY', 'FRAUD - CONFIDENCE GAMES/TRICKERY', 'FRAUD - CREDIT CARD/ATM', 'FRAUD - UNAUTHORIZED USE OF CONVEYANCE', 'FRAUD - FALSE PRETENSE', 'FRAUD - IMPERSONATION', 'FRAUD - WIRE/COMPUTER/OTHER ELECTRONIC', 'FRAUD - WORTHLESS CHECKS', 'FRAUD-FAIL TO RETURN RENTAL VEHICLE', 'FRAUD-HACKING/COMPUTER INVASION', 'FRAUD-WELFARE FRAUD'],\n", " 'Assault': ['SIMPLE ASSAULT', 'AGGRAVATED ASSAULT'],\n", " 'Drugs': ['DRUG/NARCOTIC VIOLATIONS', 'DRUG EQUIPMENT/PARAPHERNALIA'],\n", " 'Sexual Offenses': ['SEX OFFENSE - FORCIBLE RAPE', 'SEX OFFENSE - SEXUAL ASSAULT WITH AN OBJECT', 'SEX OFFENSE - FONDLING', 'SEX OFFENSE - INDECENT EXPOSURE', 'SEX OFFENSE - FORCIBLE SODOMY', 'SEX OFFENSE - STATUTORY RAPE', 'SEX OFFENSE - PEEPING TOM', 'SEX OFFENSE - INCEST'],\n", " 'Homicide': ['HOMICIDE-MURDER/NON-NEGLIGENT MANSLAUGHTER', 'JUSTIFIABLE HOMICIDE', 'HOMICIDE - NEGLIGENT MANSLAUGHTER'],\n", " 'Arson': ['ARSON'],\n", " 'Kidnapping': ['KIDNAPPING/ABDUCTION'],\n", " 'Weapons Violations': ['WEAPON VIOLATIONS'],\n", " 'Traffic Violations': ['ALL TRAFFIC (EXCEPT DWI)'],\n", " 'Disorderly Conduct': ['DISORDERLY CONDUCT', 'DISORDERLY CONDUCT-DRUNK AND DISRUPTIVE', 'DISORDERLY CONDUCT-FIGHTING (AFFRAY)', 'DISORDERLY CONDUCT-UNLAWFUL ASSEMBLY'],\n", " 'Gambling': ['GAMBLING - OPERATING/PROMOTING/ASSISTING', 'GAMBLING - BETTING/WAGERING'],\n", " 'Animal-related Offenses': ['ANIMAL CRUELTY'],\n", " 'Prostitution-related Offenses': ['PROSTITUTION', 'PROSTITUTION - ASSISTING/PROMOTING', 'PROSTITUTION - PURCHASING']\n", "}\n", "\n", "# Function to categorize crime based on the mapping dictionary\n", "def categorize_crime(crime):\n", " for category, crimes in category_mapping.items():\n", " if crime in crimes:\n", " return category\n", " return 'Miscellaneous'\n", "\n", "# Create a new DataFrame with simplified crime categories\n", "Durham_new = pd.DataFrame({\n", " \"year\": pd.to_datetime(Durham['Report Date']).dt.year,\n", " \"city\": \"Durham\",\n", " \"crime_major_category\": Durham['Offense'].apply(categorize_crime),\n", " \"crime_detail\": Durham['Offense'].str.title(),\n", " \"latitude\": Durham['X'],\n", " \"longitude\": Durham['Y'],\n", " \"occurance_time\": pd.to_datetime(Durham['Report Date'] + ' ' + Durham['Report Time']).dt.strftime('%Y/%m/%d %H:%M:%S'),\n", " \"clear_status\": Durham['Status'],\n", " \"incident_address\": Durham['Address'],\n", " \"notes\": Durham['Weapon'].apply(lambda x: f\"Weapon: {x}\" if pd.notnull(x) else \"No Data\")\n", "})\n", "\n", "Durham_new[['latitude', 'longitude']] = Durham.apply(lambda row: convert_coordinates(row['X'], row['Y']), axis=1).round(5).fillna(0)\n" ] }, { "cell_type": "code", "execution_count": 92, "id": "c8d699cf", "metadata": {}, "outputs": [], "source": [ "Durham_new = Durham_new[Durham_new['year'] >= 2015].fillna(\"No Data\")" ] }, { "cell_type": "code", "execution_count": 93, "id": "fe3be70e", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
yearcitycrime_major_categorycrime_detaillatitudelongitudeoccurance_timeclear_statusincident_addressnotes
1499192022DurhamTheftLarceny - From Motor Vehicle35.88024-78.850242022/04/13 00:15:00Cleared By Arrest5400 S MIAMI BLVDWeapon: (blank)
1499202022DurhamMiscellaneousRecovered Stolen Vehicle (Other Jurisdiction)35.88037-78.850572022/04/13 00:15:00Cleared By Arrest5400 S MIAMI BLVDWeapon: (blank)
1499212022DurhamAssaultAggravated Assault35.96519-78.945592022/12/10 01:55:00Cleared By Exception3200 OLD CHAPEL HILL RDWeapon: Handgun
1499222022DurhamTheftVandalism35.88496-78.845672022/12/31 00:00:00Active/Open100 TATUM DRWeapon: (blank)
1499232022DurhamFraudFraud - Credit Card/Atm35.99019-78.891112022/05/03 08:36:00Cleared By Arrest800 E MAIN STWeapon: (blank)
\n", "
" ], "text/plain": [ " year city crime_major_category \\\n", "149919 2022 Durham Theft \n", "149920 2022 Durham Miscellaneous \n", "149921 2022 Durham Assault \n", "149922 2022 Durham Theft \n", "149923 2022 Durham Fraud \n", "\n", " crime_detail latitude longitude \\\n", "149919 Larceny - From Motor Vehicle 35.88024 -78.85024 \n", "149920 Recovered Stolen Vehicle (Other Jurisdiction) 35.88037 -78.85057 \n", "149921 Aggravated Assault 35.96519 -78.94559 \n", "149922 Vandalism 35.88496 -78.84567 \n", "149923 Fraud - Credit Card/Atm 35.99019 -78.89111 \n", "\n", " occurance_time clear_status incident_address \\\n", "149919 2022/04/13 00:15:00 Cleared By Arrest 5400 S MIAMI BLVD \n", "149920 2022/04/13 00:15:00 Cleared By Arrest 5400 S MIAMI BLVD \n", "149921 2022/12/10 01:55:00 Cleared By Exception 3200 OLD CHAPEL HILL RD \n", "149922 2022/12/31 00:00:00 Active/Open 100 TATUM DR \n", "149923 2022/05/03 08:36:00 Cleared By Arrest 800 E MAIN ST \n", "\n", " notes \n", "149919 Weapon: (blank) \n", "149920 Weapon: (blank) \n", "149921 Weapon: Handgun \n", "149922 Weapon: (blank) \n", "149923 Weapon: (blank) " ] }, "execution_count": 93, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Durham_new.tail(5)" ] }, { "cell_type": "code", "execution_count": 94, "id": "55fc0352", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(149922, 10)" ] }, "execution_count": 94, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Durham_new.shape" ] }, { "cell_type": "markdown", "id": "1a87d3c7", "metadata": {}, "source": [ "# Chapel Hill" ] }, { "cell_type": "code", "execution_count": 90, "id": "9f002d85", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "Chapel = pd.read_csv(\"Chapel_hill.csv\", low_memory=False)" ] }, { "cell_type": "markdown", "id": "20afd6f7", "metadata": {}, "source": [ "## Exploratory Data Analysis" ] }, { "cell_type": "code", "execution_count": 22, "id": "00878dd6", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "Index(['X', 'Y', 'Incident_ID', 'Agency', 'Offense', 'Street', 'City', 'State',\n", " 'Zipcode', 'Date_of_Report', 'Date_of_Occurrence', 'Date_Found',\n", " 'Reported_As', 'Premise_Description', 'Forcible', 'Weapon_Description',\n", " 'Victim_Age', 'Victim_Race', 'Victim_Gender', 'Latitude', 'Longitude',\n", " 'ObjectId'],\n", " dtype='object')" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Chapel.columns" ] }, { "cell_type": "code", "execution_count": 95, "id": "30789db9", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array(['', 'DISTURBANCE/NUI', 'SUSPICIOUS/WANT', 'TRAFFIC STOP',\n", " 'THEFT/LARCENY', 'MISC OFFICER IN', 'BURGLARY/HOME I',\n", " 'INDECENCY/LEWDN', 'TRAFFIC/TRANSPO', 'MVC W INJURY',\n", " 'DAMAGE/VANDALIS', 'PUBLIC SERVICE', 'TRESPASSING/UNW',\n", " 'INFO MESSAGE', 'HARASSMENT/STAL', 'DOMESTIC DISTUR',\n", " 'ADMINISTRATIVE', 'ELECTRICAL HAZA', 'CARDIAC ARREST',\n", " 'FRAUD OR DECEPT', 'ASSIST CITIZEN', 'ASSAULT/SEXUAL',\n", " 'INTOXICATED SUB', 'LE ASSISTANCE', 'DRUGS', 'SUSPICIOUS OR W',\n", " 'ARREST', 'DISPUTE', 'DISTURBANCE', 'BURGLARY', 'ASSIST OTHR AGE',\n", " 'LARCENY FROM AU', 'TRESPASSING', 'DAMAGE TO PROPE',\n", " 'REFUSAL TO LEAV', 'UNKNOWN PROBLEM', 'WEAPON/FIREARMS',\n", " 'LOUD NOISE', 'ESCORT', 'ABDUCTION/CUSTO', 'VANDALISM',\n", " 'LARCENY OF OTHE', 'LARCENY FROM PE', 'THREATS', 'LARCENY FROM BU',\n", " 'BURGLAR ALARM', 'DOMESTIC', 'CARDIAC RESP AR', 'PROPERTY FOUND',\n", " 'ASSAULT', 'FIREWORKS', 'MISSING/RUNAWAY', 'OVERDOSE',\n", " 'SEXUAL OFFENSE', 'MENTAL DISORDER', 'CHECK WELL BEIN',\n", " 'SUSPICIOUS COND', 'PSYCHIATRIC', 'OPEN DOOR', 'ABANDONED AUTO',\n", " 'HARASSMENT THRE', 'TRAFFIC VIOLATI', 'ANIMAL BITE',\n", " 'LARCENY OF BIKE', 'SOLICITATION', 'JUVENILE RELATE',\n", " 'ASSIST MOTORIST', 'ANIMAL', 'ANIMAL CALL', 'HAZARDOUS DRIVI',\n", " 'LARCENY FROM RE', 'LARCENY OF AUTO', 'MVC', 'SUICIDE ATTEMPT',\n", " 'GAS LEAK FIRE', 'MISSING PERSON', 'ASSIST OTHER AG',\n", " 'PUBLICE SERVICE', 'DOMESTIC ASSIST', 'BURGLARY ATTEMP',\n", " 'SUSPICIOUS VEHI', 'STAB GUNSHOT PE', 'UNKNOWN LE',\n", " 'ROBBERY/CARJACK', 'MOTOR VEHICLE C', 'ALARMS', '911 HANGUP',\n", " 'STRUCTURE FIRE', 'ABUSE/ABANDOMEN', 'VEHICLE FIRE', 'EXPLOSION',\n", " 'DECEASED PERSON', 'DRIVING UNDER I', 'GUNSHOT INJURY',\n", " 'SCHOOL PATROL', 'ACTIVE ASSAILAN', 'BOMB/CBRN/PRODU',\n", " 'STATIONARY PATR', 'LITTERING', 'HOUSE CHECK', 'STAB GSW OR PEN',\n", " 'CARDIAC', 'CLOSE PATROL', 'BOMB FOUND/SUSP', 'STRUCTURE COLLA',\n", " 'INFO FOR ALL UN', 'MVC ENTRAPMENT', 'UNCONCIOUS OR F',\n", " 'LIFTING ASSISTA', 'ATTEMPT TO LOCA', 'SICK PERSON',\n", " 'HEAT OR COLD EX', 'CONFINED SPACE', 'TRAUMATIC INJUR',\n", " 'MVC W INJURY AB', 'MVC W INJURY DE', 'DROWNING', 'CITY ORDINANCE'],\n", " dtype=object)" ] }, "execution_count": 95, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Chapel['Reported_As'].unique()" ] }, { "cell_type": "code", "execution_count": 96, "id": "11ff26fb", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array(['', 'HANDGUN', 'UNKNOWN', 'PERSONAL WEAPONS', 'NONE',\n", " 'SHOTGUN', 'OTHER FIREARM', 'OTHER', 'RIFLE', 'UNARMED',\n", " 'FIREARM (TYP NOT STATED)', 'KNIFE/CUTTING INSTRUMENT',\n", " 'DRUGS/NARCOTICS/SLEEPING PILLS', 'BLUNT OBJECT',\n", " 'FIREARM (TYPE NOT STATED)', 'MOTOR VEHICLE',\n", " 'FIRE/INCENDIARY DEVICE', 'POISON', 'EXPLOSIVES', nan,\n", " 'ASPHYXIATION'], dtype=object)" ] }, "execution_count": 96, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Chapel['Weapon_Description'].unique()" ] }, { "cell_type": "code", "execution_count": 97, "id": "245de78f", "metadata": {}, "outputs": [], "source": [ "# Replace specified values with None\n", "replace_values = {'': None, 'NONE': None}\n", "Chapel['Weapon_Description'] = Chapel['Weapon_Description'].replace(replace_values)" ] }, { "cell_type": "code", "execution_count": 98, "id": "f3bca6d3", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
yearcitycrime_major_categorycrime_detaillatitudelongitudeoccurance_timeclear_statusincident_addressnotes
1018552023Chapel HillDisorderly ConductAssist Carrboro35.90967-79.065062023/06/24 20:43:00No DataW FRANKLIN ST N MERRITT MILL RDWeapon: None
1018562023Chapel HillTheftLarceny From Motor Vehicle35.92758-79.030222023/09/12 17:45:00No DataWILLOW DR S ESTES DRWeapon: None
1018572023Chapel HillTraffic ViolationsInformation35.96392-79.064552023/10/03 15:59:00No DataWEAVER DAIRY RD EXT PALAFOX DRWeapon: None
1018582023Chapel HillAssaultDisturbing The Peace35.91316-79.055782023/10/27 05:40:00No DataW FRANKLIN ST N COLUMBIA STWeapon: Knife/Cutting Instrument
1018592023Chapel HillMiscellaneousLost Property35.91137-79.060412023/05/20 22:30:00No DataW FRANKLIN STYWeapon: None
\n", "
" ], "text/plain": [ " year city crime_major_category crime_detail \\\n", "101855 2023 Chapel Hill Disorderly Conduct Assist Carrboro \n", "101856 2023 Chapel Hill Theft Larceny From Motor Vehicle \n", "101857 2023 Chapel Hill Traffic Violations Information \n", "101858 2023 Chapel Hill Assault Disturbing The Peace \n", "101859 2023 Chapel Hill Miscellaneous Lost Property \n", "\n", " latitude longitude occurance_time clear_status \\\n", "101855 35.90967 -79.06506 2023/06/24 20:43:00 No Data \n", "101856 35.92758 -79.03022 2023/09/12 17:45:00 No Data \n", "101857 35.96392 -79.06455 2023/10/03 15:59:00 No Data \n", "101858 35.91316 -79.05578 2023/10/27 05:40:00 No Data \n", "101859 35.91137 -79.06041 2023/05/20 22:30:00 No Data \n", "\n", " incident_address notes \n", "101855 W FRANKLIN ST N MERRITT MILL RD Weapon: None \n", "101856 WILLOW DR S ESTES DR Weapon: None \n", "101857 WEAVER DAIRY RD EXT PALAFOX DR Weapon: None \n", "101858 W FRANKLIN ST N COLUMBIA ST Weapon: Knife/Cutting Instrument \n", "101859 W FRANKLIN STY Weapon: None " ] }, "execution_count": 98, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Create a mapping for crime categories\n", "category_mapping = {\n", " 'Theft': ['THEFT/LARCENY', 'LARCENY FROM AU', 'LARCENY FROM PE', 'LARCENY OF OTHE', 'LARCENY FROM BU', 'LARCENY OF BIKE', 'LARCENY FROM RE', 'LARCENY OF AUTO'],\n", " 'Assault': ['ASSAULT/SEXUAL', 'ASSAULT', 'STAB GUNSHOT PE', 'ACTIVE ASSAILAN'],\n", " 'Burglary': ['BURGLARY', 'BURGLARY ATTEMP', 'STRUCTURE COLLAPSE', 'ROBBERY/CARJACK'],\n", " 'Drugs': ['DRUGS'],\n", " 'Traffic Violations': ['TRAFFIC STOP', 'TRAFFIC/TRANSPO', 'TRAFFIC VIOLATI', 'MVC', 'MVC W INJURY', 'MVC W INJURY AB', 'MVC W INJURY DE', 'MVC ENTRAPMENT'],\n", " 'Disorderly Conduct': ['DISTURBANCE/NUI', 'DOMESTIC DISTUR', 'DISPUTE', 'DISTURBANCE', 'LOST PROPERTY', 'TRESPASSING/UNW', 'REFUSAL TO LEAV', 'SUSPICIOUS COND', 'STRUCTURE FIRE'],\n", " 'Fraud': ['FRAUD OR DECEPT'],\n", " 'Sexual Offenses': ['SEXUAL OFFENSE'],\n", " 'Homicide': ['SUICIDE ATTEMPT', 'ABUSE/ABANDOMEN', 'DECEASED PERSON'],\n", " 'Weapons Violations': ['WEAPON/FIREARMS'],\n", " 'Animal-related Offenses': ['ANIMAL BITE', 'ANIMAL', 'ANIMAL CALL'],\n", " 'Missing Person': ['MISSING PERSON'],\n", " 'Public Service': ['PUBLIC SERVICE', 'PUBLICE SERVICE'],\n", " 'Miscellaneous': ['', 'SUSPICIOUS/WANT', 'MISC OFFICER IN', 'INDECENCY/LEWDN', 'PUBLIC SERVICE', 'TRESPASSING', 'UNKNOWN PROBLEM', 'LOUD NOISE', 'ESCORT', 'ABDUCTION/CUSTO', 'THREATS', 'BURGLAR ALARM', 'DOMESTIC', 'PROPERTY FOUND', 'FIREWORKS', 'MISSING/RUNAWAY', 'MENTAL DISORDER', 'CHECK WELL BEIN', 'PSYCHIATRIC', 'OPEN DOOR', 'ABANDONED AUTO', 'HARASSMENT THRE', 'JUVENILE RELATE', 'ASSIST MOTORIST', 'HAZARDOUS DRIVI', 'MVC', 'GAS LEAK FIRE', 'ASSIST OTHER AG', 'DOMESTIC ASSIST', 'SUSPICIOUS VEHI', 'UNKNOWN LE', 'ALARMS', '911 HANGUP', 'BOMB/CBRN/PRODU', 'STATIONARY PATR', 'LITTERING', 'HOUSE CHECK', 'CARDIAC', 'CLOSE PATROL', 'BOMB FOUND/SUSP', 'INFO FOR ALL UN', 'UNCONCIOUS OR F', 'LIFTING ASSISTA', 'ATTEMPT TO LOCA', 'SICK PERSON', 'HEAT OR COLD EX', 'CONFINED SPACE', 'TRAUMATIC INJUR', 'DROWNING', 'CITY ORDINANCE']\n", "}\n", "\n", "\n", "# Function to categorize crime based on the mapping dictionary\n", "def categorize_crime(crime):\n", " for category, crimes in category_mapping.items():\n", " if crime in crimes:\n", " return category\n", " return 'Miscellaneous'\n", "\n", "# Create a new DataFrame with simplified crime categories\n", "Chapel_new = pd.DataFrame({\n", " \"year\": pd.to_datetime(Chapel['Date_of_Occurrence']).dt.year,\n", " \"city\": \"Chapel Hill\",\n", " \"crime_major_category\": Chapel['Reported_As'].apply(categorize_crime),\n", " \"crime_detail\": Chapel['Offense'].str.title(),\n", " \"latitude\": Chapel['X'].round(5).fillna(0),\n", " \"longitude\": Chapel['Y'].round(5).fillna(0),\n", " \"occurance_time\": pd.to_datetime(Chapel['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\": Chapel['Street'].str.replace(\"@\", \" \"),\n", " \"notes\": Chapel['Weapon_Description'].apply(lambda x: f\"Weapon: {x}\" if pd.notnull(x) else \"Weapon: None\").str.title()\n", "}).fillna(\"No Data\")\n", "\n", "Chapel_new = Chapel_new[Chapel_new['year'] >= 2015]\n", "Chapel_new.tail()" ] }, { "cell_type": "code", "execution_count": 100, "id": "303148b6", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(67010, 10)" ] }, "execution_count": 100, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Chapel_new.shape" ] }, { "cell_type": "markdown", "id": "80403d93", "metadata": {}, "source": [ "# Charlotte" ] }, { "cell_type": "code", "execution_count": 101, "id": "c8a782e3", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "Charlotte = pd.read_csv(\"Charlotte.csv\", low_memory = False)" ] }, { "cell_type": "markdown", "id": "65e574af", "metadata": {}, "source": [ "## Exploratory Data Analysis" ] }, { "cell_type": "code", "execution_count": 102, "id": "2014125e", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array(['Open', 'Cleared by Other Means', 'Victim Chose not to Prosecute',\n", " 'Cleared by Arrest', 'Located (Missing Persons and Runaways only)',\n", " 'Unfounded', 'Unfounded-Referred to Other Agency',\n", " 'Cleared, Pending Arrest Validation',\n", " 'Cleared by Arrest by Another Agency',\n", " 'Prosecution Declined by DA', 'By Death of Offender',\n", " 'Extradition Declined'], dtype=object)" ] }, "execution_count": 102, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Charlotte['CLEARANCE_DETAIL_STATUS'].unique()" ] }, { "cell_type": "code", "execution_count": 103, "id": "8c68d990", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "Index(['X', 'Y', 'YEAR', 'INCIDENT_REPORT_ID', 'LOCATION', 'CITY', 'STATE',\n", " 'ZIP', 'X_COORD_PUBLIC', 'Y_COORD_PUBLIC', 'LATITUDE_PUBLIC',\n", " 'LONGITUDE_PUBLIC', 'DIVISION_ID', 'CMPD_PATROL_DIVISION', 'NPA',\n", " 'DATE_REPORTED', 'DATE_INCIDENT_BEGAN', 'DATE_INCIDENT_END',\n", " 'ADDRESS_DESCRIPTION', 'LOCATION_TYPE_DESCRIPTION',\n", " 'PLACE_TYPE_DESCRIPTION', 'PLACE_DETAIL_DESCRIPTION',\n", " 'CLEARANCE_STATUS', 'CLEARANCE_DETAIL_STATUS', 'CLEARANCE_DATE',\n", " 'HIGHEST_NIBRS_CODE', 'HIGHEST_NIBRS_DESCRIPTION', 'OBJECTID', 'Shape',\n", " 'GlobalID'],\n", " dtype='object')" ] }, "execution_count": 103, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Charlotte.columns" ] }, { "cell_type": "code", "execution_count": 104, "id": "16b564ce", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array(['Identity Theft', 'All Other Offenses', 'Theft From Motor Vehicle',\n", " 'Shoplifting', 'All Other Thefts', 'Credit Card/Teller Fraud',\n", " 'Forcible Fondling', 'Damage/Vandalism Of Property',\n", " 'Intimidation', 'Drug/Narcotic Violations',\n", " 'Other Unlisted Non-Criminal', 'Simple Assault',\n", " 'Motor Vehicle Theft', 'Missing Person', 'Embezzlement',\n", " 'Forcible Rape', 'Aggravated Assault', 'Burglary/B&E',\n", " 'Theft From Building', 'Impersonation', 'False Pretenses/Swindle',\n", " 'Extortion/Blackmail', 'Arson', 'Vehicle Recovery', 'Suicide',\n", " 'Sudden/Natural Death Investigation', 'Affray',\n", " 'Weapon Law Violations', 'Trespass Of Real Property', 'Murder',\n", " 'Driving Under The Influence', 'Stolen Property Offenses',\n", " 'Robbery', 'Overdose', 'Theft of Motor Vehicle Parts from Vehicle',\n", " 'Hacking/Computer Invasion', 'Counterfeiting/Forgery',\n", " 'Kidnapping', 'Drug Equipment Violations',\n", " 'Fire (Accidental/Non-Arson)', 'Pornography/Obscene Material',\n", " 'Disorderly Conduct', 'Indecent Exposure', 'Public Accident',\n", " 'Pocket-Picking', 'Peeping Tom', 'Purse-Snatching',\n", " 'Liquor Law Violations', 'Statutory Rape', 'Wire Fraud',\n", " 'Family Offenses; Nonviolent', 'Incest', 'Forcible Sodomy',\n", " 'Theft From Coin-Operated Machine Or Device',\n", " 'Human Trafficking, Involuntary Servitude',\n", " 'Human Trafficking, Commercial Sex Acts', 'Justifiable Homicide',\n", " 'Curfew/Loitering/Vagrancy Violations', 'Negligent Manslaughter',\n", " 'Worthless Check: Felony (over $2000)', 'Animal Cruelty',\n", " 'Sexual Assault With Object', 'Assisting Gambling',\n", " 'Dog Bite/Animal Control Incident', 'Prostitution',\n", " 'Assisting Prostitution', 'Gambling Equipment Violations',\n", " 'Betting/Wagering', 'Welfare Fraud', 'Purchasing Prostitution',\n", " 'Gas Leak', 'Bribery'], dtype=object)" ] }, "execution_count": 104, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Charlotte['HIGHEST_NIBRS_DESCRIPTION'].unique()" ] }, { "cell_type": "code", "execution_count": 128, "id": "f5adcb4c", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
yearcitycrime_major_categorycrime_detaillatitudelongitudeoccurance_timeclear_statusincident_addressnotes
6611372017CharlotteAssaultAggravated Assault35.22712-80.734572017/01/01 00:00:00Open4400 GAYNELLE DRLocation Type Description: Indoors; Place Type...
6611382017CharlotteMiscellaneousDamage/Vandalism Of Property35.25992-80.899292017/01/01 00:00:00Open1100 MARBLE STLocation Type Description: Indoors; Place Type...
6611392017CharlotteAssaultSimple Assault35.05221-80.851272017/01/01 00:00:00Cleared by Arrest14800 BALLANTYNE VILLAGE WYLocation Type Description: Outdoors; Place Typ...
6611402017CharlotteMiscellaneousDamage/Vandalism Of Property35.26302-80.845832017/01/01 00:00:00Open2100 KENNESAW DRLocation Type Description: Indoors; Place Type...
6611412017CharlotteDisorderly ConductDisorderly Conduct35.20613-80.795142017/01/01 00:00:00Cleared by Arrest2700 E INDEPENDENCE BVLocation Type Description: Other; Place Type D...
\n", "
" ], "text/plain": [ " year city crime_major_category crime_detail \\\n", "661137 2017 Charlotte Assault Aggravated Assault \n", "661138 2017 Charlotte Miscellaneous Damage/Vandalism Of Property \n", "661139 2017 Charlotte Assault Simple Assault \n", "661140 2017 Charlotte Miscellaneous Damage/Vandalism Of Property \n", "661141 2017 Charlotte Disorderly Conduct Disorderly Conduct \n", "\n", " latitude longitude occurance_time clear_status \\\n", "661137 35.22712 -80.73457 2017/01/01 00:00:00 Open \n", "661138 35.25992 -80.89929 2017/01/01 00:00:00 Open \n", "661139 35.05221 -80.85127 2017/01/01 00:00:00 Cleared by Arrest \n", "661140 35.26302 -80.84583 2017/01/01 00:00:00 Open \n", "661141 35.20613 -80.79514 2017/01/01 00:00:00 Cleared by Arrest \n", "\n", " incident_address \\\n", "661137 4400 GAYNELLE DR \n", "661138 1100 MARBLE ST \n", "661139 14800 BALLANTYNE VILLAGE WY \n", "661140 2100 KENNESAW DR \n", "661141 2700 E INDEPENDENCE BV \n", "\n", " notes \n", "661137 Location Type Description: Indoors; Place Type... \n", "661138 Location Type Description: Indoors; Place Type... \n", "661139 Location Type Description: Outdoors; Place Typ... \n", "661140 Location Type Description: Indoors; Place Type... \n", "661141 Location Type Description: Other; Place Type D... " ] }, "execution_count": 128, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df = Charlotte\n", "df = Charlotte\n", "category_mapping = {\n", " 'Theft': [\n", " 'Identity Theft', 'Theft From Motor Vehicle', 'Shoplifting', 'All Other Thefts',\n", " 'Credit Card/Teller Fraud', 'Motor Vehicle Theft', 'Theft From Building',\n", " 'Theft of Motor Vehicle Parts from Vehicle', 'Purse-Snatching', 'Pocket-Picking',\n", " 'Theft From Coin-Operated Machine Or Device'\n", " ],\n", " 'Fraud': [\n", " 'Credit Card/Teller Fraud', 'Embezzlement', 'Impersonation', 'False Pretenses/Swindle',\n", " 'Extortion/Blackmail', 'Counterfeiting/Forgery', 'Welfare Fraud', 'Wire Fraud',\n", " 'Hacking/Computer Invasion'\n", " ],\n", " 'Assault': [\n", " 'Forcible Fondling', 'Simple Assault', 'Aggravated Assault', 'Forcible Rape',\n", " 'Intimidation', 'Sexual Assault With Object', 'Statutory Rape', 'Incest',\n", " 'Forcible Sodomy', 'Affray'\n", " ],\n", " 'Drugs': [\n", " 'Drug/Narcotic Violations', 'Drug Equipment Violations'\n", " ],\n", " 'Sexual Offenses': [\n", " 'Forcible Rape', 'Forcible Fondling', 'Sexual Assault With Object',\n", " 'Indecent Exposure', 'Peeping Tom', 'Statutory Rape', 'Incest', 'Forcible Sodomy'\n", " ],\n", " 'Homicide': [\n", " 'Murder', 'Justifiable Homicide', 'Negligent Manslaughter'\n", " ],\n", " 'Arson': [\n", " 'Arson', 'Fire (Accidental/Non-Arson)'\n", " ],\n", " 'Kidnapping': [\n", " 'Kidnapping'\n", " ],\n", " 'Weapons Violations': [\n", " 'Weapon Law Violations'\n", " ],\n", " 'Traffic Violations': [\n", " 'Driving Under The Influence'\n", " ],\n", " 'Disorderly Conduct': [\n", " 'Disorderly Conduct', 'Public Accident'\n", " ],\n", " 'Gambling': [\n", " 'Assisting Gambling', 'Gambling Equipment Violations', 'Betting/Wagering'\n", " ],\n", " 'Animal-related Offenses': [\n", " 'Animal Cruelty', 'Dog Bite/Animal Control Incident'\n", " ],\n", " 'Prostitution-related Offenses': [\n", " 'Prostitution', 'Assisting Prostitution', 'Purchasing Prostitution'\n", " ]\n", "}\n", "\n", "# Function to categorize crime based on the mapping dictionary\n", "def categorize_crime(crime):\n", " for category, crimes in category_mapping.items():\n", " if crime in crimes:\n", " return category\n", " return 'Miscellaneous'\n", "\n", "Charlotte_new = pd.DataFrame({\n", " \"year\": df['YEAR'],\n", " \"city\": \"Charlotte\",\n", " \"crime_major_category\": df['HIGHEST_NIBRS_DESCRIPTION'].apply(categorize_crime),\n", " \"crime_detail\": df['HIGHEST_NIBRS_DESCRIPTION'],\n", " \"latitude\": df['LATITUDE_PUBLIC'].round(5).fillna(0),\n", " \"longitude\": df['LONGITUDE_PUBLIC'].round(5).fillna(0),\n", " \"occurance_time\": pd.to_datetime(df['DATE_INCIDENT_BEGAN'].str.replace(r'\\+\\d{2}$', '', regex=True), errors='coerce').dt.strftime('%Y/%m/%d %H:%M:%S'),\n", " \"clear_status\": df['CLEARANCE_DETAIL_STATUS'],\n", " \"incident_address\": df['LOCATION'],\n", " \"notes\": 'Location Type Description: ' + df['LOCATION_TYPE_DESCRIPTION'].str.title().str.replace('_', ' ') + '; ' +\n", " 'Place Type Description: ' + df['PLACE_TYPE_DESCRIPTION'].str.title().str.replace('_', ' ') + '; ' +\n", " 'Place Detail Description: ' + df['PLACE_DETAIL_DESCRIPTION'].str.title().str.replace('_', ' ')\n", "})\n", "\n", "Charlotte_new.dropna(subset=['occurance_time'], inplace=True)\n", "Charlotte_new.fillna(\"No Data\", inplace=True)\n", "Charlotte_new.tail()" ] }, { "cell_type": "code", "execution_count": 129, "id": "1026993f", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(661086, 10)" ] }, "execution_count": 129, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Charlotte_new.shape" ] }, { "cell_type": "markdown", "id": "ab448155", "metadata": {}, "source": [ "# Cary" ] }, { "cell_type": "code", "execution_count": 107, "id": "ec11f03c", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "Cary = pd.read_csv(\"Cary.csv\", low_memory = False).dropna(subset=['Year'])" ] }, { "cell_type": "markdown", "id": "194aec45", "metadata": {}, "source": [ "## Exploratory Data Analysis" ] }, { "cell_type": "code", "execution_count": 108, "id": "5c5249e1", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "Index(['Crime Category', 'Crime Type', 'UCR', 'Map Reference',\n", " 'Incident Number', 'Begin Date Of Occurrence',\n", " 'Begin Time Of Occurrence', 'End Date Of Occurrence',\n", " 'End Time Of Occurrence', 'Crime Day', 'Geo Code', 'Location Category',\n", " 'District', 'Beat Number', 'Location', 'ID', 'Lat', 'Lon',\n", " 'Charge Count', 'Neighborhood ID', 'Apartment Complex',\n", " 'Residential Subdivision', 'Subdivision ID', 'Phx Activity Date',\n", " 'Phx Record Status', 'Phx Community', 'Phx Status', 'Record',\n", " 'Offense Category', 'Violent Property', 'timeframe', 'domestic',\n", " 'Total Incidents', 'Year'],\n", " dtype='object')" ] }, "execution_count": 108, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Cary.columns" ] }, { "cell_type": "code", "execution_count": 84, "id": "187a83c8", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array(['ALL OTHER', 'ARSON', 'AGGRAVATED ASSAULT', 'BURGLARY',\n", " 'MOTOR VEHICLE THEFT', 'MURDER', 'ROBBERY', 'LARCENY'],\n", " dtype=object)" ] }, "execution_count": 84, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Cary['Crime Category'].unique()" ] }, { "cell_type": "code", "execution_count": 110, "id": "9f7ade9d", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
yearcitycrime_major_categorycrime_detaillatitudelongitudeoccurance_timeclear_statusincident_addressnotes
1165102022CaryMiscellaneousMissing Person35.79749-78.813582022/11/13 13:01:36No DataEDENHURST AVEDistrict: CpdnViolent Property: Non-Repor
1165462022CaryMiscellaneousMissing Person35.78252-78.815032022/10/15 15:00:00No DataBYRAMS FORD DRDistrict: CpdsViolent Property: Non-Repor
1165522022CaryMiscellaneousMissing Person35.76020-78.744272022/11/24 12:00:00No DataWALNUT STDistrict: CpdsViolent Property: Non-Repor
1165582018CaryMiscellaneousMissing Person35.82342-78.905232018/05/10 05:00:00No DataEMERALD DOWNS RDDistrict: D2Violent Property: Non-Repor
1165732023CaryMiscellaneousMissing Person35.78005-78.757332023/07/22 23:30:00No DataFENTON GATEWAY DRDistrict: CpdsViolent Property: Non-Repor
\n", "
" ], "text/plain": [ " year city crime_major_category crime_detail latitude longitude \\\n", "116510 2022 Cary Miscellaneous Missing Person 35.79749 -78.81358 \n", "116546 2022 Cary Miscellaneous Missing Person 35.78252 -78.81503 \n", "116552 2022 Cary Miscellaneous Missing Person 35.76020 -78.74427 \n", "116558 2018 Cary Miscellaneous Missing Person 35.82342 -78.90523 \n", "116573 2023 Cary Miscellaneous Missing Person 35.78005 -78.75733 \n", "\n", " occurance_time clear_status incident_address \\\n", "116510 2022/11/13 13:01:36 No Data EDENHURST AVE \n", "116546 2022/10/15 15:00:00 No Data BYRAMS FORD DR \n", "116552 2022/11/24 12:00:00 No Data WALNUT ST \n", "116558 2018/05/10 05:00:00 No Data EMERALD DOWNS RD \n", "116573 2023/07/22 23:30:00 No Data FENTON GATEWAY DR \n", "\n", " notes \n", "116510 District: CpdnViolent Property: Non-Repor \n", "116546 District: CpdsViolent Property: Non-Repor \n", "116552 District: CpdsViolent Property: Non-Repor \n", "116558 District: D2Violent Property: Non-Repor \n", "116573 District: CpdsViolent Property: Non-Repor " ] }, "execution_count": 110, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df = Cary\n", "def categorize_crime(crime):\n", " crime_mapping = {\n", " 'Theft': ['BURGLARY', 'MOTOR VEHICLE THEFT', 'LARCENY'],\n", " 'Arson': ['ARSON'],\n", " 'Assault': ['AGGRAVATED ASSAULT'],\n", " 'Homicide': ['MURDER'],\n", " 'Robbery': ['ROBBERY']\n", " }\n", "\n", " for category, crimes in crime_mapping.items():\n", " if crime in crimes:\n", " return category\n", " return 'Miscellaneous'\n", "\n", "Cary_new = 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", "Cary_new = Cary_new[Cary_new['year'] >= 2015]\n", "Cary_new.tail()\n" ] }, { "cell_type": "code", "execution_count": 111, "id": "05e9fedd", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(44413, 10)" ] }, "execution_count": 111, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Cary_new.shape" ] }, { "cell_type": "markdown", "id": "6d3ed28a", "metadata": {}, "source": [ "# Raleigh" ] }, { "cell_type": "code", "execution_count": 112, "id": "22b3f101", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "\n", "Raleigh = pd.read_csv(\"Raleigh.csv\", low_memory=False)" ] }, { "cell_type": "markdown", "id": "3633a1d1", "metadata": {}, "source": [ "## Exploratory Data Analysis" ] }, { "cell_type": "code", "execution_count": 114, "id": "6984bfa7", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "Index(['X', 'Y', 'OBJECTID', 'GlobalID', 'case_number', 'crime_category',\n", " 'crime_code', 'crime_description', 'crime_type',\n", " 'reported_block_address', 'city_of_incident', 'city', 'district',\n", " 'reported_date', 'reported_year', 'reported_month', 'reported_day',\n", " 'reported_hour', 'reported_dayofwk', 'latitude', 'longitude', 'agency',\n", " 'updated_date'],\n", " dtype='object')" ] }, "execution_count": 114, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Raleigh.columns" ] }, { "cell_type": "code", "execution_count": 140, "id": "10da0e5f", "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
yearcitycrime_major_categorycrime_detaillatitudelongitudeoccurance_timeclear_statusincident_addressnotes
4963132024RaleighMiscellaneousPornography/Obscene Material0.00.02024/01/08 12:18:00No DataNo DataDistrict: Northeast
4963142024RaleighMiscellaneousPornography/Obscene Material0.00.02024/01/08 12:18:00No DataNo DataDistrict: North
4963152024RaleighMiscellaneousPornography/Obscene Material0.00.02024/01/08 12:19:00No DataNo DataDistrict: Southeast
4963162024RaleighSexual OffensesSex Offense/Forcible Fondling0.00.02024/02/14 21:52:00No DataNo DataDistrict: North
4963172024RaleighSexual OffensesSex Offense/Statutory Rape0.00.02024/02/14 18:19:00No DataNo DataDistrict: Northwest
\n", "
" ], "text/plain": [ " year city crime_major_category crime_detail \\\n", "496313 2024 Raleigh Miscellaneous Pornography/Obscene Material \n", "496314 2024 Raleigh Miscellaneous Pornography/Obscene Material \n", "496315 2024 Raleigh Miscellaneous Pornography/Obscene Material \n", "496316 2024 Raleigh Sexual Offenses Sex Offense/Forcible Fondling \n", "496317 2024 Raleigh Sexual Offenses Sex Offense/Statutory Rape \n", "\n", " latitude longitude occurance_time clear_status \\\n", "496313 0.0 0.0 2024/01/08 12:18:00 No Data \n", "496314 0.0 0.0 2024/01/08 12:18:00 No Data \n", "496315 0.0 0.0 2024/01/08 12:19:00 No Data \n", "496316 0.0 0.0 2024/02/14 21:52:00 No Data \n", "496317 0.0 0.0 2024/02/14 18:19:00 No Data \n", "\n", " incident_address notes \n", "496313 No Data District: Northeast \n", "496314 No Data District: North \n", "496315 No Data District: Southeast \n", "496316 No Data District: North \n", "496317 No Data District: Northwest " ] }, "execution_count": 140, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Define category mapping\n", "category_mapping = {\n", " 'Miscellaneous': ['MISCELLANEOUS', 'ALL OTHER OFFENSES'],\n", " 'Sexual Offenses': ['SEX OFFENSES'],\n", " 'Assault': ['ASSAULT', 'SIMPLE ASSAULT'],\n", " 'Juvenile': ['JUVENILE'],\n", " 'Traffic Violations': ['TRAFFIC', 'UNAUTHORIZED MOTOR VEHICLE USE', 'TRAFFIC VIOLATIONS', 'LIQUOR LAW VIOLATIONS'],\n", " 'Fraud': ['FRAUD', 'EMBEZZLEMENT', 'BRIBERY'],\n", " 'Vandalism': ['VANDALISM'],\n", " 'Theft': ['LARCENY FROM MV', 'LARCENY', 'MV THEFT', 'STOLEN PROPERTY'],\n", " 'Burglary': ['BURGLARY/COMMERCIAL', 'BURGLARY/RESIDENTIAL'],\n", " 'Disorderly Conduct': ['DISORDERLY CONDUCT'],\n", " 'Weapons Violations': ['WEAPONS VIOLATION'],\n", " 'Drugs': ['DRUGS', 'DRUG VIOLATIONS'],\n", " 'Arson': ['ARSON'],\n", " 'Robbery': ['ROBBERY'],\n", " 'Kidnapping': ['KIDNAPPING'],\n", " 'Extortion': ['EXTORTION'],\n", " 'Human Trafficking': ['HUMAN TRAFFICKING'],\n", " 'Murder': ['MURDER'],\n", " 'Prostitution-related Offenses': ['PROSTITUTION'],\n", " 'Gambling': ['GAMBLING'],\n", "}\n", "\n", "# Function to categorize crime based on the mapping dictionary\n", "def categorize_crime(crime):\n", " for category, crimes in category_mapping.items():\n", " if crime in crimes:\n", " return category\n", " return 'Miscellaneous'\n", "\n", "# Create a new DataFrame with simplified crime categories\n", "Raleigh_new = pd.DataFrame({\n", " \"year\": Raleigh['reported_year'],\n", " \"city\": \"Raleigh\",\n", " \"crime_major_category\": Raleigh['crime_category'].apply(categorize_crime),\n", " \"crime_detail\": Raleigh['crime_description'],\n", " \"latitude\": Raleigh['latitude'].round(5).fillna(0),\n", " \"longitude\": Raleigh['longitude'].round(5).fillna(0),\n", " \"occurance_time\": pd.to_datetime(Raleigh['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\": Raleigh['reported_block_address'] + ', ' + Raleigh['district'] + ', Raleigh',\n", " \"notes\": 'District: '+ Raleigh['district'].str.title()\n", "}).fillna(\"No Data\")\n", "\n", "Raleigh_new = Raleigh_new[Raleigh_new['year'] >= 2015]\n", "# Display the last few rows of the new DataFrame\n", "Raleigh_new.tail()\n" ] }, { "cell_type": "code", "execution_count": 141, "id": "4561f484", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(466007, 10)" ] }, "execution_count": 141, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Raleigh_new.shape" ] }, { "cell_type": "code", "execution_count": 117, "id": "b36410ab", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "35.99118" ] }, "execution_count": 117, "metadata": {}, "output_type": "execute_result" } ], "source": [ "max(Raleigh_new['latitude'])" ] }, { "cell_type": "code", "execution_count": 118, "id": "a4faca3c", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([2017, 2016, 2015, 2018, 2019, 2020, 2021, 2022, 2023, 2024])" ] }, "execution_count": 118, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Raleigh_new['year'].unique()" ] }, { "cell_type": "markdown", "id": "e0ad795d", "metadata": {}, "source": [ "# Combined" ] }, { "cell_type": "code", "execution_count": 142, "id": "82ed2351", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
yearcitycrime_major_categorycrime_detaillatitudelongitudeoccurance_timeclear_statusincident_addressnotes
02022DurhamMiscellaneousIntimidation36.03734-78.878432022/05/20 12:00:00Cleared By Arrest3500 DEARBORN DRWeapon: (blank)
12019DurhamFraudFraud-Identity Theft35.90624-78.905562019/01/01 00:01:00Inactive4400 EMERALD FOREST DRWeapon: (blank)
22020DurhamTheftLarceny - Automobile Parts Or Accessories35.98809-78.889522020/03/09 00:00:00Active/Open100 EDGEMONT LNWeapon: (blank)
32022DurhamTheftTowed/Abandoned Vehicle35.92415-78.785322022/07/19 10:30:00Closed (Non-Criminal)1000 ANDREWS CHAPEL RDWeapon: (blank)
42018DurhamDrugsDrug/Narcotic Violations35.97721-78.895072018/10/18 14:35:00Inactive800 DUPREE STWeapon: Not Applicable/None
\n", "
" ], "text/plain": [ " year city crime_major_category \\\n", "0 2022 Durham Miscellaneous \n", "1 2019 Durham Fraud \n", "2 2020 Durham Theft \n", "3 2022 Durham Theft \n", "4 2018 Durham Drugs \n", "\n", " crime_detail latitude longitude \\\n", "0 Intimidation 36.03734 -78.87843 \n", "1 Fraud-Identity Theft 35.90624 -78.90556 \n", "2 Larceny - Automobile Parts Or Accessories 35.98809 -78.88952 \n", "3 Towed/Abandoned Vehicle 35.92415 -78.78532 \n", "4 Drug/Narcotic Violations 35.97721 -78.89507 \n", "\n", " occurance_time clear_status incident_address \\\n", "0 2022/05/20 12:00:00 Cleared By Arrest 3500 DEARBORN DR \n", "1 2019/01/01 00:01:00 Inactive 4400 EMERALD FOREST DR \n", "2 2020/03/09 00:00:00 Active/Open 100 EDGEMONT LN \n", "3 2022/07/19 10:30:00 Closed (Non-Criminal) 1000 ANDREWS CHAPEL RD \n", "4 2018/10/18 14:35:00 Inactive 800 DUPREE ST \n", "\n", " notes \n", "0 Weapon: (blank) \n", "1 Weapon: (blank) \n", "2 Weapon: (blank) \n", "3 Weapon: (blank) \n", "4 Weapon: Not Applicable/None " ] }, "execution_count": 142, "metadata": {}, "output_type": "execute_result" } ], "source": [ "NC = pd.concat([Durham_new, Chapel_new, Charlotte_new, Cary_new, Raleigh_new], ignore_index=True)\n", "NC.head()" ] }, { "cell_type": "code", "execution_count": 143, "id": "ebd44953", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(1388438, 10)" ] }, "execution_count": 143, "metadata": {}, "output_type": "execute_result" } ], "source": [ "NC.shape" ] }, { "cell_type": "code", "execution_count": 138, "id": "51b553ae", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "RangeIndex: 1388438 entries, 0 to 1388437\n", "Data columns (total 10 columns):\n", " # Column Non-Null Count Dtype \n", "--- ------ -------------- ----- \n", " 0 year 1388438 non-null int64 \n", " 1 city 1388438 non-null object \n", " 2 crime_major_category 1388438 non-null object \n", " 3 crime_detail 1388438 non-null object \n", " 4 latitude 1388438 non-null float64\n", " 5 longitude 1388438 non-null float64\n", " 6 occurance_time 1388438 non-null object \n", " 7 clear_status 1388438 non-null object \n", " 8 incident_address 1388438 non-null object \n", " 9 notes 1388438 non-null object \n", "dtypes: float64(2), int64(1), object(7)\n", "memory usage: 105.9+ MB\n" ] } ], "source": [ "NC.info()" ] }, { "cell_type": "code", "execution_count": 144, "id": "5c45ae42", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array(['Miscellaneous', 'Fraud', 'Theft', 'Drugs', 'Assault',\n", " 'Sexual Offenses', 'Traffic Violations', 'Kidnapping',\n", " 'Weapons Violations', 'Homicide', 'Disorderly Conduct', 'Arson',\n", " 'Animal-related Offenses', 'Prostitution-related Offenses',\n", " 'Gambling', 'Public Service', 'Burglary', 'Missing Person',\n", " 'Robbery', 'Juvenile', 'Vandalism', 'Extortion',\n", " 'Human Trafficking', 'Murder'], dtype=object)" ] }, "execution_count": 144, "metadata": {}, "output_type": "execute_result" } ], "source": [ "NC['crime_major_category'].unique()" ] }, { "cell_type": "code", "execution_count": 147, "id": "7fdffffb", "metadata": {}, "outputs": [], "source": [ "NC.to_csv('NC_dataset.csv', index=False)\n" ] }, { "cell_type": "code", "execution_count": 124, "id": "489faa5b", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "year int64\n", "city object\n", "crime_major_category object\n", "crime_detail object\n", "latitude float64\n", "longitude float64\n", "occurance_time object\n", "clear_status object\n", "incident_address object\n", "notes object\n", "dtype: object\n" ] } ], "source": [ "print(NC.dtypes)" ] }, { "cell_type": "code", "execution_count": 145, "id": "b4885d64", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024])" ] }, "execution_count": 145, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import numpy as np\n", "np.sort(NC['year'].unique())" ] } ], "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 }