{
"cells": [
{
"cell_type": "markdown",
"id": "6a85f28c",
"metadata": {},
"source": [
"# Introduction"
]
},
{
"cell_type": "markdown",
"id": "4bb5aaa8",
"metadata": {},
"source": [
"This is the 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": "aaee9c05",
"metadata": {},
"source": [
"## Exploratory Data Analysis"
]
},
{
"cell_type": "code",
"execution_count": 87,
"id": "16c2b839",
"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",
" year | \n",
" city | \n",
" crime_major_category | \n",
" crime_detail | \n",
" latitude | \n",
" longitude | \n",
" occurance_time | \n",
" clear_status | \n",
" incident_address | \n",
" notes | \n",
"
\n",
" \n",
" \n",
" \n",
" 149919 | \n",
" 2022 | \n",
" Durham | \n",
" Theft | \n",
" Larceny - From Motor Vehicle | \n",
" 35.88024 | \n",
" -78.85024 | \n",
" 2022/04/13 00:15:00 | \n",
" Cleared By Arrest | \n",
" 5400 S MIAMI BLVD | \n",
" Weapon: (blank) | \n",
"
\n",
" \n",
" 149920 | \n",
" 2022 | \n",
" Durham | \n",
" Miscellaneous | \n",
" Recovered Stolen Vehicle (Other Jurisdiction) | \n",
" 35.88037 | \n",
" -78.85057 | \n",
" 2022/04/13 00:15:00 | \n",
" Cleared By Arrest | \n",
" 5400 S MIAMI BLVD | \n",
" Weapon: (blank) | \n",
"
\n",
" \n",
" 149921 | \n",
" 2022 | \n",
" Durham | \n",
" Assault | \n",
" Aggravated Assault | \n",
" 35.96519 | \n",
" -78.94559 | \n",
" 2022/12/10 01:55:00 | \n",
" Cleared By Exception | \n",
" 3200 OLD CHAPEL HILL RD | \n",
" Weapon: Handgun | \n",
"
\n",
" \n",
" 149922 | \n",
" 2022 | \n",
" Durham | \n",
" Theft | \n",
" Vandalism | \n",
" 35.88496 | \n",
" -78.84567 | \n",
" 2022/12/31 00:00:00 | \n",
" Active/Open | \n",
" 100 TATUM DR | \n",
" Weapon: (blank) | \n",
"
\n",
" \n",
" 149923 | \n",
" 2022 | \n",
" Durham | \n",
" Fraud | \n",
" Fraud - Credit Card/Atm | \n",
" 35.99019 | \n",
" -78.89111 | \n",
" 2022/05/03 08:36:00 | \n",
" Cleared By Arrest | \n",
" 800 E MAIN ST | \n",
" Weapon: (blank) | \n",
"
\n",
" \n",
"
\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": "b6052404",
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"Chapel = pd.read_csv(\"Chapel_hill.csv\", low_memory=False)"
]
},
{
"cell_type": "markdown",
"id": "502ffe3b",
"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": "a31a68f4",
"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": "10ccc474",
"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",
" year | \n",
" city | \n",
" crime_major_category | \n",
" crime_detail | \n",
" latitude | \n",
" longitude | \n",
" occurance_time | \n",
" clear_status | \n",
" incident_address | \n",
" notes | \n",
"
\n",
" \n",
" \n",
" \n",
" 101855 | \n",
" 2023 | \n",
" Chapel Hill | \n",
" Disorderly Conduct | \n",
" Assist Carrboro | \n",
" 35.90967 | \n",
" -79.06506 | \n",
" 2023/06/24 20:43:00 | \n",
" No Data | \n",
" W FRANKLIN ST N MERRITT MILL RD | \n",
" Weapon: None | \n",
"
\n",
" \n",
" 101856 | \n",
" 2023 | \n",
" Chapel Hill | \n",
" Theft | \n",
" Larceny From Motor Vehicle | \n",
" 35.92758 | \n",
" -79.03022 | \n",
" 2023/09/12 17:45:00 | \n",
" No Data | \n",
" WILLOW DR S ESTES DR | \n",
" Weapon: None | \n",
"
\n",
" \n",
" 101857 | \n",
" 2023 | \n",
" Chapel Hill | \n",
" Traffic Violations | \n",
" Information | \n",
" 35.96392 | \n",
" -79.06455 | \n",
" 2023/10/03 15:59:00 | \n",
" No Data | \n",
" WEAVER DAIRY RD EXT PALAFOX DR | \n",
" Weapon: None | \n",
"
\n",
" \n",
" 101858 | \n",
" 2023 | \n",
" Chapel Hill | \n",
" Assault | \n",
" Disturbing The Peace | \n",
" 35.91316 | \n",
" -79.05578 | \n",
" 2023/10/27 05:40:00 | \n",
" No Data | \n",
" W FRANKLIN ST N COLUMBIA ST | \n",
" Weapon: Knife/Cutting Instrument | \n",
"
\n",
" \n",
" 101859 | \n",
" 2023 | \n",
" Chapel Hill | \n",
" Miscellaneous | \n",
" Lost Property | \n",
" 35.91137 | \n",
" -79.06041 | \n",
" 2023/05/20 22:30:00 | \n",
" No Data | \n",
" W FRANKLIN STY | \n",
" Weapon: None | \n",
"
\n",
" \n",
"
\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": "dbbee2b7",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(67010, 10)"
]
},
"execution_count": 100,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Chapel_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": "afa8a880",
"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",
" year | \n",
" city | \n",
" crime_major_category | \n",
" crime_detail | \n",
" latitude | \n",
" longitude | \n",
" occurance_time | \n",
" clear_status | \n",
" incident_address | \n",
" notes | \n",
"
\n",
" \n",
" \n",
" \n",
" 116510 | \n",
" 2022 | \n",
" Cary | \n",
" Miscellaneous | \n",
" Missing Person | \n",
" 35.79749 | \n",
" -78.81358 | \n",
" 2022/11/13 13:01:36 | \n",
" No Data | \n",
" EDENHURST AVE | \n",
" District: CpdnViolent Property: Non-Repor | \n",
"
\n",
" \n",
" 116546 | \n",
" 2022 | \n",
" Cary | \n",
" Miscellaneous | \n",
" Missing Person | \n",
" 35.78252 | \n",
" -78.81503 | \n",
" 2022/10/15 15:00:00 | \n",
" No Data | \n",
" BYRAMS FORD DR | \n",
" District: CpdsViolent Property: Non-Repor | \n",
"
\n",
" \n",
" 116552 | \n",
" 2022 | \n",
" Cary | \n",
" Miscellaneous | \n",
" Missing Person | \n",
" 35.76020 | \n",
" -78.74427 | \n",
" 2022/11/24 12:00:00 | \n",
" No Data | \n",
" WALNUT ST | \n",
" District: CpdsViolent Property: Non-Repor | \n",
"
\n",
" \n",
" 116558 | \n",
" 2018 | \n",
" Cary | \n",
" Miscellaneous | \n",
" Missing Person | \n",
" 35.82342 | \n",
" -78.90523 | \n",
" 2018/05/10 05:00:00 | \n",
" No Data | \n",
" EMERALD DOWNS RD | \n",
" District: D2Violent Property: Non-Repor | \n",
"
\n",
" \n",
" 116573 | \n",
" 2023 | \n",
" Cary | \n",
" Miscellaneous | \n",
" Missing Person | \n",
" 35.78005 | \n",
" -78.75733 | \n",
" 2023/07/22 23:30:00 | \n",
" No Data | \n",
" FENTON GATEWAY DR | \n",
" District: CpdsViolent Property: Non-Repor | \n",
"
\n",
" \n",
"
\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": "840ca1f4",
"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",
" year | \n",
" city | \n",
" crime_major_category | \n",
" crime_detail | \n",
" latitude | \n",
" longitude | \n",
" occurance_time | \n",
" clear_status | \n",
" incident_address | \n",
" notes | \n",
"
\n",
" \n",
" \n",
" \n",
" 496313 | \n",
" 2024 | \n",
" Raleigh | \n",
" Miscellaneous | \n",
" Pornography/Obscene Material | \n",
" 0.0 | \n",
" 0.0 | \n",
" 2024/01/08 12:18:00 | \n",
" No Data | \n",
" No Data | \n",
" District: Northeast | \n",
"
\n",
" \n",
" 496314 | \n",
" 2024 | \n",
" Raleigh | \n",
" Miscellaneous | \n",
" Pornography/Obscene Material | \n",
" 0.0 | \n",
" 0.0 | \n",
" 2024/01/08 12:18:00 | \n",
" No Data | \n",
" No Data | \n",
" District: North | \n",
"
\n",
" \n",
" 496315 | \n",
" 2024 | \n",
" Raleigh | \n",
" Miscellaneous | \n",
" Pornography/Obscene Material | \n",
" 0.0 | \n",
" 0.0 | \n",
" 2024/01/08 12:19:00 | \n",
" No Data | \n",
" No Data | \n",
" District: Southeast | \n",
"
\n",
" \n",
" 496316 | \n",
" 2024 | \n",
" Raleigh | \n",
" Sexual Offenses | \n",
" Sex Offense/Forcible Fondling | \n",
" 0.0 | \n",
" 0.0 | \n",
" 2024/02/14 21:52:00 | \n",
" No Data | \n",
" No Data | \n",
" District: North | \n",
"
\n",
" \n",
" 496317 | \n",
" 2024 | \n",
" Raleigh | \n",
" Sexual Offenses | \n",
" Sex Offense/Statutory Rape | \n",
" 0.0 | \n",
" 0.0 | \n",
" 2024/02/14 18:19:00 | \n",
" No Data | \n",
" No Data | \n",
" District: Northwest | \n",
"
\n",
" \n",
"
\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": 149,
"id": "82ed2351",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"\n",
"\n",
"
\n",
" \n",
" \n",
" | \n",
" year | \n",
" city | \n",
" crime_major_category | \n",
" crime_detail | \n",
" latitude | \n",
" longitude | \n",
" occurance_time | \n",
" clear_status | \n",
" incident_address | \n",
" notes | \n",
"
\n",
" \n",
" \n",
" \n",
" 0 | \n",
" 2022 | \n",
" Durham | \n",
" Miscellaneous | \n",
" Intimidation | \n",
" 36.03734 | \n",
" -78.87843 | \n",
" 2022/05/20 12:00:00 | \n",
" Cleared By Arrest | \n",
" 3500 DEARBORN DR | \n",
" Weapon: (blank) | \n",
"
\n",
" \n",
" 1 | \n",
" 2019 | \n",
" Durham | \n",
" Fraud | \n",
" Fraud-Identity Theft | \n",
" 35.90624 | \n",
" -78.90556 | \n",
" 2019/01/01 00:01:00 | \n",
" Inactive | \n",
" 4400 EMERALD FOREST DR | \n",
" Weapon: (blank) | \n",
"
\n",
" \n",
" 2 | \n",
" 2020 | \n",
" Durham | \n",
" Theft | \n",
" Larceny - Automobile Parts Or Accessories | \n",
" 35.98809 | \n",
" -78.88952 | \n",
" 2020/03/09 00:00:00 | \n",
" Active/Open | \n",
" 100 EDGEMONT LN | \n",
" Weapon: (blank) | \n",
"
\n",
" \n",
" 3 | \n",
" 2022 | \n",
" Durham | \n",
" Theft | \n",
" Towed/Abandoned Vehicle | \n",
" 35.92415 | \n",
" -78.78532 | \n",
" 2022/07/19 10:30:00 | \n",
" Closed (Non-Criminal) | \n",
" 1000 ANDREWS CHAPEL RD | \n",
" Weapon: (blank) | \n",
"
\n",
" \n",
" 4 | \n",
" 2018 | \n",
" Durham | \n",
" Drugs | \n",
" Drug/Narcotic Violations | \n",
" 35.97721 | \n",
" -78.89507 | \n",
" 2018/10/18 14:35:00 | \n",
" Inactive | \n",
" 800 DUPREE ST | \n",
" Weapon: Not Applicable/None | \n",
"
\n",
" \n",
"
\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": 149,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"NC = pd.concat([Durham_new, Chapel_new, Cary_new, Raleigh_new], ignore_index=True)\n",
"NC.head()"
]
},
{
"cell_type": "code",
"execution_count": 150,
"id": "ebd44953",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(727352, 10)"
]
},
"execution_count": 150,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"NC.shape"
]
},
{
"cell_type": "code",
"execution_count": 151,
"id": "51b553ae",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"RangeIndex: 727352 entries, 0 to 727351\n",
"Data columns (total 10 columns):\n",
" # Column Non-Null Count Dtype \n",
"--- ------ -------------- ----- \n",
" 0 year 727352 non-null int64 \n",
" 1 city 727352 non-null object \n",
" 2 crime_major_category 727352 non-null object \n",
" 3 crime_detail 727352 non-null object \n",
" 4 latitude 727352 non-null float64\n",
" 5 longitude 727352 non-null float64\n",
" 6 occurance_time 727352 non-null object \n",
" 7 clear_status 727352 non-null object \n",
" 8 incident_address 727352 non-null object \n",
" 9 notes 727352 non-null object \n",
"dtypes: float64(2), int64(1), object(7)\n",
"memory usage: 55.5+ MB\n"
]
}
],
"source": [
"NC.info()"
]
},
{
"cell_type": "code",
"execution_count": 152,
"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": 152,
"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": 153,
"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": 154,
"id": "b4885d64",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024])"
]
},
"execution_count": 154,
"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
}