Upload data_cleaning.py
Browse files- data_cleaning.py +91 -0
data_cleaning.py
ADDED
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
'''
|
2 |
+
git clone https://github.com/geopandas/geopandas.git
|
3 |
+
cd geopandas
|
4 |
+
pip install .
|
5 |
+
'''
|
6 |
+
import requests
|
7 |
+
import pandas as pd
|
8 |
+
import numpy as np
|
9 |
+
import requests
|
10 |
+
import geopandas as gpd
|
11 |
+
from shapely.geometry import Point
|
12 |
+
|
13 |
+
# load neighborhood GeoJson file and housing dataset
|
14 |
+
neighborhood = gpd.read_file("https://raw.githubusercontent.com/HathawayLiu/Housing_dataset/main/Neighborhood_Map_Atlas_Districts.geojson")
|
15 |
+
url = "https://github.com/HathawayLiu/Housing_dataset/raw/main/Building_Permits_20240213.csv"
|
16 |
+
df = pd.read_csv(url)
|
17 |
+
|
18 |
+
# Pre-processing of data
|
19 |
+
df['OriginalZip'] = pd.to_numeric(df['OriginalZip'], errors='coerce').fillna('NA').astype(str)
|
20 |
+
df['OriginalZip'] = df['OriginalZip'].replace(0, 'NA')
|
21 |
+
df['OriginalCity'] = df['OriginalCity'].fillna('SEATTLE')
|
22 |
+
df['OriginalState'] = df['OriginalState'].fillna('WA')
|
23 |
+
df['EstProjectCost'] = pd.to_numeric(df['EstProjectCost'], errors='coerce').astype(float)
|
24 |
+
df['IssuedDate'] = pd.to_datetime(df['IssuedDate'], errors='coerce')
|
25 |
+
df['HousingUnits'] = pd.to_numeric(df['HousingUnits'], errors='coerce').fillna(0).astype(int)
|
26 |
+
df['HousingUnitsRemoved'] = pd.to_numeric(df['HousingUnitsRemoved'], errors='coerce').fillna(0).astype(int)
|
27 |
+
df['HousingUnitsAdded'] = pd.to_numeric(df['HousingUnitsAdded'], errors='coerce').fillna(0).astype(int)
|
28 |
+
df['Longitude'] = pd.to_numeric(df['Longitude'], errors='coerce')
|
29 |
+
df['Latitude'] = pd.to_numeric(df['Latitude'], errors='coerce')
|
30 |
+
|
31 |
+
# Function to get the zip code from coordinates
|
32 |
+
def get_zip_code_from_coordinates(latitude, longitude, api_key):
|
33 |
+
if pd.isna(latitude) or pd.isna(longitude):
|
34 |
+
return 'NA' # Return 'NA' if latitude or longitude is NaN
|
35 |
+
|
36 |
+
api_url = f"https://maps.googleapis.com/maps/api/geocode/json?latlng={latitude},{longitude}&key={api_key}"
|
37 |
+
response = requests.get(api_url)
|
38 |
+
|
39 |
+
if response.status_code == 200:
|
40 |
+
data = response.json()
|
41 |
+
if data['results']:
|
42 |
+
for component in data['results'][0]['address_components']:
|
43 |
+
if 'postal_code' in component['types']:
|
44 |
+
return component['long_name']
|
45 |
+
return 'NA' # Return 'NA' if no zip code found
|
46 |
+
else:
|
47 |
+
return 'NA' # Return 'NA' for non-200 responses
|
48 |
+
|
49 |
+
# Apply the function only to rows where 'OriginalZip' is 'NA'
|
50 |
+
api_key = 'Your Own API Key'
|
51 |
+
for index, row in df.iterrows():
|
52 |
+
if row['OriginalZip'] == 'NA':
|
53 |
+
zip_code = get_zip_code_from_coordinates(row['Latitude'], row['Longitude'], api_key)
|
54 |
+
df.at[index, 'OriginalZip'] = zip_code
|
55 |
+
print(f"Updated row {index} with Zip Code: {zip_code}")
|
56 |
+
|
57 |
+
# Function to get corresponding neighborhood district from coordinates
|
58 |
+
gdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.Longitude, df.Latitude), crs='EPSG:4326')
|
59 |
+
def get_neighborhood_name(point, neighborhoods):
|
60 |
+
for _, row in neighborhoods.iterrows():
|
61 |
+
if point.within(row['geometry']):
|
62 |
+
print(row['L_HOOD'])
|
63 |
+
return row['L_HOOD']
|
64 |
+
return 'NA'
|
65 |
+
# Apply the function to each row
|
66 |
+
gdf['NeighborDistrict'] = gdf['geometry'].apply(lambda x: get_neighborhood_name(x, neighborhood) if pd.notna(x) else 'NA')
|
67 |
+
# Merge the new column back to the original DataFrame
|
68 |
+
df['NeighborDistrict'] = gdf['NeighborDistrict']
|
69 |
+
# filtered df to start from year 2000
|
70 |
+
df_filtered = df[df['IssuedDate'].dt.year >= 2000]
|
71 |
+
df_filtered['IssuedDate'] = df['IssuedDate'].astype(str)
|
72 |
+
df_filtered.fillna('NA', inplace=True)
|
73 |
+
|
74 |
+
'''
|
75 |
+
Following code is for spliting datasets in train and test dataset
|
76 |
+
'''
|
77 |
+
# Read the dataset
|
78 |
+
housing_df = pd.read_csv('https://github.com/HathawayLiu/Housing_dataset/raw/main/Building_Permits_Cleaned.csv')
|
79 |
+
# Shuffle the dataset
|
80 |
+
housing_df = housing_df.sample(frac=1).reset_index(drop=True)
|
81 |
+
|
82 |
+
# Splitting the dataset into training and test sets
|
83 |
+
split_ratio = 0.8 # 80% for training, 20% for testing
|
84 |
+
split_index = int(len(housing_df) * split_ratio)
|
85 |
+
|
86 |
+
train_df = housing_df[:split_index]
|
87 |
+
test_df = housing_df[split_index:]
|
88 |
+
|
89 |
+
# Export to CSV
|
90 |
+
train_df.to_csv('/Users/hathawayliu/Desktop/train_dataset.csv', index=False)
|
91 |
+
test_df.to_csv('/Users/hathawayliu/Desktop/test_dataset.csv', index=False)
|