zwn22 commited on
Commit
2b0b978
1 Parent(s): 6eb7b56

Update NC_Crime.py

Browse files
Files changed (1) hide show
  1. NC_Crime.py +50 -44
NC_Crime.py CHANGED
@@ -84,8 +84,8 @@ class NCCrimeDataset(datasets.GeneratorBasedBuilder):
84
  def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]:
85
  # Use the raw GitHub link to download the CSV file
86
  cary_path = dl_manager.download_and_extract("https://data.townofcary.org/api/explore/v2.1/catalog/datasets/cpd-incidents/exports/csv?lang=en&timezone=US%2FEastern&use_labels=true&delimiter=%2C")
87
- durham_path = dl_manager.download_and_extract("https://www.arcgis.com/sharing/rest/content/items/7132216432df4957830593359b0c4030/data")
88
- # chapel_hill_path = dl_manager.download_and_extract("https://drive.google.com/uc?export=download&id=19cZzyedCLUtQt9Ko4bcOixWIJHBn9CfI")
89
  # raleigh_path = dl_manager.download_and_extract("https://drive.google.com/uc?export=download&id=1SZi4e01TxwuDDb6k9EU_7i-qTP1Xq2sm")
90
  # Cary
91
  # "https://data.townofcary.org/api/explore/v2.1/catalog/datasets/cpd-incidents/exports/csv?lang=en&timezone=US%2FEastern&use_labels=true&delimiter=%2C",
@@ -97,13 +97,13 @@ class NCCrimeDataset(datasets.GeneratorBasedBuilder):
97
  # "https://drive.google.com/uc?export=download&id=1SZi4e01TxwuDDb6k9EU_7i-qTP1Xq2sm"
98
 
99
  cary_df = self._preprocess_cary(cary_path)
100
- durham_df = self._preprocess_durham(durham_path)
101
  # raleigh_df = self._preprocess_raleigh(raleigh_path)
102
- # chapel_hill_df = self._preprocess_chapel_hill(chapel_hill_path)
103
 
104
  # combined_df = pd.concat([cary_df, durham_df, raleigh_df, chapel_hill_df], ignore_index=True)
105
 
106
- combined_df = pd.concat([cary_df, durham_df], ignore_index=True)
107
 
108
 
109
  combined_file_path = os.path.join(dl_manager.download_dir, "combined_dataset.csv")
@@ -114,56 +114,62 @@ class NCCrimeDataset(datasets.GeneratorBasedBuilder):
114
  ]
115
 
116
 
117
- def _preprocess_durham(self, file_path):
118
- # Load the dataset
119
- Durham = pd.read_excel(file_path)
120
-
121
- # Clean the 'Weapon' column
122
- Durham['Weapon'] = Durham['Weapon'].replace(['(blank)', 'Not Applicable/None', 'Unknown/Not Stated'], None)
123
-
 
124
  # Define the category mapping
125
  category_mapping = {
126
- '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'],
127
- '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'],
128
- 'Assault': ['SIMPLE ASSAULT', 'AGGRAVATED ASSAULT'],
129
- 'Drugs': ['DRUG/NARCOTIC VIOLATIONS', 'DRUG EQUIPMENT/PARAPHERNALIA'],
130
- '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'],
131
- 'Homicide': ['HOMICIDE-MURDER/NON-NEGLIGENT MANSLAUGHTER', 'JUSTIFIABLE HOMICIDE', 'HOMICIDE - NEGLIGENT MANSLAUGHTER'],
132
- 'Arson': ['ARSON'],
133
- 'Kidnapping': ['KIDNAPPING/ABDUCTION'],
134
- 'Weapons Violations': ['WEAPON VIOLATIONS'],
135
- 'Traffic Violations': ['ALL TRAFFIC (EXCEPT DWI)'],
136
- 'Disorderly Conduct': ['DISORDERLY CONDUCT', 'DISORDERLY CONDUCT-DRUNK AND DISRUPTIVE', 'DISORDERLY CONDUCT-FIGHTING (AFFRAY)', 'DISORDERLY CONDUCT-UNLAWFUL ASSEMBLY'],
137
- 'Gambling': ['GAMBLING - OPERATING/PROMOTING/ASSISTING', 'GAMBLING - BETTING/WAGERING'],
138
- 'Animal-related Offenses': ['ANIMAL CRUELTY'],
139
- 'Prostitution-related Offenses': ['PROSTITUTION', 'PROSTITUTION - ASSISTING/PROMOTING', 'PROSTITUTION - PURCHASING']
140
  }
141
-
142
- # Function to categorize crime
143
  def categorize_crime(crime):
144
  for category, crimes in category_mapping.items():
145
  if crime in crimes:
146
  return category
147
  return 'Miscellaneous'
148
-
149
- # Coordinate transformation function
150
- def convert_coordinates(x, y):
151
- transformer = Transformer.from_crs("epsg:2264", "epsg:4326", always_xy=True)
152
- lon, lat = transformer.transform(x, y)
153
- return pd.Series([lat, lon])
154
-
155
  # Create a new DataFrame with simplified crime categories
156
- Durham_new = pd.DataFrame({
157
- # Your DataFrame creation code
158
- })
 
 
 
 
 
 
 
 
 
159
 
160
- # Convert coordinates and round/fill missing values
161
- Durham_new[['latitude', 'longitude']] = Durham.apply(lambda row: convert_coordinates(row['X'], row['Y']), axis=1).round(5).fillna(0)
162
-
163
- # Filter records and handle missing values
164
- Durham_new = Durham_new[Durham_new['year'] >= 2015].fillna("No Data")
 
 
 
165
 
166
- return Durham_new
167
 
168
  def _preprocess_cary(self, file_path):
169
  # Load the dataset
 
84
  def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]:
85
  # Use the raw GitHub link to download the CSV file
86
  cary_path = dl_manager.download_and_extract("https://data.townofcary.org/api/explore/v2.1/catalog/datasets/cpd-incidents/exports/csv?lang=en&timezone=US%2FEastern&use_labels=true&delimiter=%2C")
87
+ # durham_path = dl_manager.download_and_extract("https://www.arcgis.com/sharing/rest/content/items/7132216432df4957830593359b0c4030/data")
88
+ chapel_hill_path = dl_manager.download_and_extract("https://drive.google.com/uc?export=download&id=19cZzyedCLUtQt9Ko4bcOixWIJHBn9CfI")
89
  # raleigh_path = dl_manager.download_and_extract("https://drive.google.com/uc?export=download&id=1SZi4e01TxwuDDb6k9EU_7i-qTP1Xq2sm")
90
  # Cary
91
  # "https://data.townofcary.org/api/explore/v2.1/catalog/datasets/cpd-incidents/exports/csv?lang=en&timezone=US%2FEastern&use_labels=true&delimiter=%2C",
 
97
  # "https://drive.google.com/uc?export=download&id=1SZi4e01TxwuDDb6k9EU_7i-qTP1Xq2sm"
98
 
99
  cary_df = self._preprocess_cary(cary_path)
100
+ # durham_df = self._preprocess_durham(durham_path)
101
  # raleigh_df = self._preprocess_raleigh(raleigh_path)
102
+ chapel_hill_df = self._preprocess_chapel_hill(chapel_hill_path)
103
 
104
  # combined_df = pd.concat([cary_df, durham_df, raleigh_df, chapel_hill_df], ignore_index=True)
105
 
106
+ combined_df = pd.concat([cary_df, chapel_hill_df], ignore_index=True)
107
 
108
 
109
  combined_file_path = os.path.join(dl_manager.download_dir, "combined_dataset.csv")
 
114
  ]
115
 
116
 
117
+ def _preprocess_chapel_hill(self, file_path):
118
+ # Load the dataset
119
+ Chapel = pd.read_csv(file_path, low_memory=False)
120
+
121
+ # Replace specified values with None
122
+ replace_values = {'<Null>': None, 'NONE': None}
123
+ Chapel['Weapon_Description'] = Chapel['Weapon_Description'].replace(replace_values)
124
+
125
  # Define the category mapping
126
  category_mapping = {
127
+ 'Theft': ['THEFT/LARCENY', 'LARCENY FROM AU', 'LARCENY FROM PE', 'LARCENY OF OTHE', 'LARCENY FROM BU', 'LARCENY OF BIKE', 'LARCENY FROM RE', 'LARCENY OF AUTO'],
128
+ 'Assault': ['ASSAULT/SEXUAL', 'ASSAULT', 'STAB GUNSHOT PE', 'ACTIVE ASSAILAN'],
129
+ 'Burglary': ['BURGLARY', 'BURGLARY ATTEMP', 'STRUCTURE COLLAPSE', 'ROBBERY/CARJACK'],
130
+ 'Drugs': ['DRUGS'],
131
+ 'Traffic Violations': ['TRAFFIC STOP', 'TRAFFIC/TRANSPO', 'TRAFFIC VIOLATI', 'MVC', 'MVC W INJURY', 'MVC W INJURY AB', 'MVC W INJURY DE', 'MVC ENTRAPMENT'],
132
+ 'Disorderly Conduct': ['DISTURBANCE/NUI', 'DOMESTIC DISTUR', 'DISPUTE', 'DISTURBANCE', 'LOST PROPERTY', 'TRESPASSING/UNW', 'REFUSAL TO LEAV', 'SUSPICIOUS COND', 'STRUCTURE FIRE'],
133
+ 'Fraud': ['FRAUD OR DECEPT'],
134
+ 'Sexual Offenses': ['SEXUAL OFFENSE'],
135
+ 'Homicide': ['SUICIDE ATTEMPT', 'ABUSE/ABANDOMEN', 'DECEASED PERSON'],
136
+ 'Weapons Violations': ['WEAPON/FIREARMS'],
137
+ 'Animal-related Offenses': ['ANIMAL BITE', 'ANIMAL', 'ANIMAL CALL'],
138
+ 'Missing Person': ['MISSING PERSON'],
139
+ 'Public Service': ['PUBLIC SERVICE', 'PUBLICE SERVICE'],
140
+ 'Miscellaneous': ['<Null>', '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']
141
  }
142
+ # Function to categorize crime
 
143
  def categorize_crime(crime):
144
  for category, crimes in category_mapping.items():
145
  if crime in crimes:
146
  return category
147
  return 'Miscellaneous'
148
+
 
 
 
 
 
 
149
  # Create a new DataFrame with simplified crime categories
150
+ Chapel_new = pd.DataFrame({
151
+ "year": pd.to_datetime(Chapel['Date_of_Occurrence']).dt.year,
152
+ "city": "Chapel Hill",
153
+ "crime_major_category": Chapel['Reported_As'].apply(categorize_crime),
154
+ "crime_detail": Chapel['Offense'].str.title(),
155
+ "latitude": Chapel['X'].round(5).fillna(0),
156
+ "longitude": Chapel['Y'].round(5).fillna(0),
157
+ "occurance_time": pd.to_datetime(Chapel['Date_of_Occurrence'].str.replace(r'\+\d{2}$', '', regex=True)).dt.strftime('%Y/%m/%d %H:%M:%S'),
158
+ "clear_status": None,
159
+ "incident_address": Chapel['Street'].str.replace("@", " "),
160
+ "notes": Chapel['Weapon_Description'].apply(lambda x: f"Weapon: {x}" if pd.notnull(x) else "Weapon: None").str.title()
161
+ }).fillna("No Data")
162
 
163
+ # Correct the latitude and longitude if necessary
164
+ Chapel_new.loc[(Chapel_new['latitude'].between(-80, -70)) & (Chapel_new['longitude'].between(30, 40)), ['latitude', 'longitude']] = Chapel_new.loc[(Chapel_new['latitude'].between(-80, -70)) & (Chapel_new['longitude'].between(30, 40)), ['longitude', 'latitude']].values
165
+
166
+ # Ensure latitude and longitude are in the expected range
167
+ Chapel_new = Chapel_new.loc[(Chapel_new['latitude'].between(30, 40)) & (Chapel_new['longitude'].between(-80, -70))]
168
+
169
+ # Filter for years 2015 and onwards
170
+ Chapel_new = Chapel_new[Chapel_new['year'] >= 2015]
171
 
172
+ return Chapel_new
173
 
174
  def _preprocess_cary(self, file_path):
175
  # Load the dataset