Spaces:
Sleeping
Sleeping
File size: 15,415 Bytes
d51d337 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 | """
Data Processing Module for Dubai Real Estate Analysis
Handles data loading, cleaning, and preprocessing for Sales, Rental, and Supply data
"""
import pandas as pd
import numpy as np
from typing import Dict, List, Tuple, Optional
from utils.helpers import normalize_area_name, validate_dataframe
from config import SALES_COLUMNS, RENTAL_COLUMNS, SUPPLY_COLUMNS
class DataProcessor:
"""Processes and prepares real estate data for analysis"""
def __init__(self, sales_data_path: str = None, rental_data_path: str = None, supply_data_path: str = None):
"""
Initialize data processor
Args:
sales_data_path: Path to the CSV/Excel file containing sale data
rental_data_path: Path to the CSV/Excel file containing rental data
supply_data_path: Path to the CSV/Excel file containing supply data
"""
self.sales_data_path = sales_data_path
self.rental_data_path = rental_data_path
self.supply_data_path = supply_data_path
self.sales_df = None
self.rental_df = None
self.supply_df = None
self.processed_sales_df = None
self.processed_rental_df = None
self.processed_supply_df = None
def load_file(self, file_path: str) -> pd.DataFrame:
"""Load CSV or Excel file"""
try:
if file_path.endswith('.csv'):
return pd.read_csv(file_path)
elif file_path.endswith(('.xlsx', '.xls')):
return pd.read_excel(file_path)
else:
raise ValueError(f"Unsupported file format: {file_path}")
except Exception as e:
print(f"Error loading file {file_path}: {e}")
raise
def load_sales_data(self, file_path: str = None) -> pd.DataFrame:
"""Load sales data from CSV/Excel file"""
if file_path:
self.sales_data_path = file_path
if self.sales_data_path:
self.sales_df = self.load_file(self.sales_data_path)
print(f"Loaded {len(self.sales_df)} sales records")
return self.sales_df
else:
raise ValueError("Sales data path not provided")
def load_rental_data(self, file_path: str = None) -> pd.DataFrame:
"""Load rental data from CSV/Excel file"""
if file_path:
self.rental_data_path = file_path
if self.rental_data_path:
self.rental_df = self.load_file(self.rental_data_path)
print(f"Loaded {len(self.rental_df)} rental records")
return self.rental_df
else:
print("Warning: Rental data path not provided")
return None
def load_supply_data(self, file_path: str = None) -> pd.DataFrame:
"""Load supply data from CSV/Excel file"""
if file_path:
self.supply_data_path = file_path
if self.supply_data_path:
self.supply_df = self.load_file(self.supply_data_path)
print(f"Loaded {len(self.supply_df)} supply records")
return self.supply_df
else:
print("Warning: Supply data path not provided")
return None
def load_all_data(self, sales_path: str = None, rental_path: str = None, supply_path: str = None):
"""Load all available data sources"""
if sales_path:
self.load_sales_data(sales_path)
elif self.sales_data_path:
self.load_sales_data()
if rental_path:
self.load_rental_data(rental_path)
elif self.rental_data_path:
self.load_rental_data()
if supply_path:
self.load_supply_data(supply_path)
elif self.supply_data_path:
self.load_supply_data()
def clean_sales_data(self) -> pd.DataFrame:
"""Clean and preprocess sales data"""
if self.sales_df is None:
raise ValueError("Sales data not loaded. Call load_sales_data() first.")
df = self.sales_df.copy()
# Standardize area names using helper function
if 'AREA_EN' in df.columns:
df['AREA_EN'] = df['AREA_EN'].apply(normalize_area_name)
# Remove any rows with missing critical data
required_cols = ['YEAR', 'AREA_EN', 'AVG_PRICE', 'MEDIAN_RATE_PER_SQFT']
df = df.dropna(subset=[col for col in required_cols if col in df.columns])
# Ensure numeric columns are numeric
numeric_cols = ['YEAR', 'AVG_PRICE', 'SALE_VALUE', 'MAX_RATE_PER_SQFT',
'MEDIAN_RATE_PER_SQFT', 'MIN_RATE_PER_SQFT', 'SALE_TRANSACTIONS']
for col in numeric_cols:
if col in df.columns:
df[col] = pd.to_numeric(df[col], errors='coerce')
# Remove outliers (prices > 3 standard deviations)
for col in ['AVG_PRICE', 'MEDIAN_RATE_PER_SQFT']:
if col in df.columns:
mean = df[col].mean()
std = df[col].std()
if std > 0:
df = df[(df[col] >= mean - 3*std) & (df[col] <= mean + 3*std)]
self.processed_sales_df = df
return df
def clean_rental_data(self) -> pd.DataFrame:
"""Clean and preprocess rental data"""
if self.rental_df is None:
return None
df = self.rental_df.copy()
# Standardize area names using helper function
if 'AREA_EN' in df.columns:
df['AREA_EN'] = df['AREA_EN'].apply(normalize_area_name)
# Remove rows with missing critical data
required_cols = ['YEAR', 'AREA_EN', 'MEDIAN_RATE_PER_SQFT']
df = df.dropna(subset=[col for col in required_cols if col in df.columns])
# Ensure numeric columns are numeric
numeric_cols = ['YEAR', 'AVG_PRICE', 'RENT_VALUE', 'MAX_RATE_PER_SQFT',
'MEDIAN_RATE_PER_SQFT', 'MIN_RATE_PER_SQFT', 'RENT_TRANSACTIONS']
for col in numeric_cols:
if col in df.columns:
df[col] = pd.to_numeric(df[col], errors='coerce')
self.processed_rental_df = df
return df
def clean_supply_data(self) -> pd.DataFrame:
"""Clean and preprocess supply data"""
if self.supply_df is None:
return None
df = self.supply_df.copy()
# Standardize area names
if 'area_name_en' in df.columns:
df['area_name_en'] = df['area_name_en'].str.lower().str.strip()
elif 'AREA_NAME_EN' in df.columns:
df['AREA_NAME_EN'] = df['AREA_NAME_EN'].str.lower().str.strip()
# Parse dates
date_cols = ['project_start_date', 'project_end_date', 'completion_date', 'cancellation_date']
for col in date_cols:
if col in df.columns:
df[col] = pd.to_datetime(df[col], errors='coerce')
# Ensure numeric columns
numeric_cols = ['no_of_units', 'no_of_buildings', 'no_of_villas', 'no_of_lands', 'percent_completed']
for col in numeric_cols:
if col in df.columns:
df[col] = pd.to_numeric(df[col], errors='coerce')
self.processed_supply_df = df
return df
def clean_all_data(self):
"""Clean all loaded data sources"""
self.clean_sales_data()
if self.rental_df is not None:
self.clean_rental_data()
if self.supply_df is not None:
self.clean_supply_data()
def get_area_list(self) -> List[str]:
"""Get list of unique areas from sales data"""
if self.processed_sales_df is None:
self.clean_sales_data()
return sorted(self.processed_sales_df['AREA_EN'].unique().tolist())
def get_year_range(self) -> Tuple[int, int]:
"""Get min and max years in sales dataset"""
if self.processed_sales_df is None:
self.clean_sales_data()
return int(self.processed_sales_df['YEAR'].min()), int(self.processed_sales_df['YEAR'].max())
def get_area_sales_data(self, area_name: str) -> pd.DataFrame:
"""Get all sales data for a specific area"""
if self.processed_sales_df is None:
self.clean_sales_data()
area_name = area_name.lower().strip()
return self.processed_sales_df[self.processed_sales_df['AREA_EN'] == area_name].copy()
def get_area_rental_data(self, area_name: str) -> Optional[pd.DataFrame]:
"""Get all rental data for a specific area"""
if self.processed_rental_df is None:
return None
area_name = area_name.lower().strip()
return self.processed_rental_df[self.processed_rental_df['AREA_EN'] == area_name].copy()
def get_latest_sales_data(self, year: int = None) -> pd.DataFrame:
"""Get latest year sales data or specific year"""
if self.processed_sales_df is None:
self.clean_sales_data()
if year is None:
year = int(self.processed_sales_df['YEAR'].max())
return self.processed_sales_df[self.processed_sales_df['YEAR'] == year].copy()
def get_latest_rental_data(self, year: int = None) -> Optional[pd.DataFrame]:
"""Get latest year rental data or specific year"""
if self.processed_rental_df is None:
return None
if year is None:
year = int(self.processed_rental_df['YEAR'].max())
return self.processed_rental_df[self.processed_rental_df['YEAR'] == year].copy()
def get_area_rental_rate(self, area_name: str, year: int = None) -> Optional[float]:
"""Get median rental rate per sqft for an area"""
if self.processed_rental_df is None:
return None
area_name = area_name.lower().strip()
area_rental = self.processed_rental_df[self.processed_rental_df['AREA_EN'] == area_name]
if year:
area_rental = area_rental[area_rental['YEAR'] == year]
if len(area_rental) > 0:
return float(area_rental['MEDIAN_RATE_PER_SQFT'].median())
return None
def get_supply_by_area(self, area_name: str) -> Optional[pd.DataFrame]:
"""Get supply data for a specific area"""
if self.processed_supply_df is None:
return None
area_name = area_name.lower().strip()
area_col = 'area_name_en' if 'area_name_en' in self.processed_supply_df.columns else 'AREA_NAME_EN'
if area_col in self.processed_supply_df.columns:
return self.processed_supply_df[
self.processed_supply_df[area_col].str.lower().str.strip() == area_name
].copy()
return None
def get_supply_summary(self, area_name: str = None) -> Dict:
"""Get supply summary statistics"""
if self.processed_supply_df is None:
return {}
df = self.processed_supply_df.copy()
if area_name:
area_col = 'area_name_en' if 'area_name_en' in df.columns else 'AREA_NAME_EN'
if area_col in df.columns:
area_name = area_name.lower().strip()
df = df[df[area_col].str.lower().str.strip() == area_name]
summary = {
"total_projects": len(df),
"total_units": int(df['no_of_units'].sum()) if 'no_of_units' in df.columns else 0,
"total_buildings": int(df['no_of_buildings'].sum()) if 'no_of_buildings' in df.columns else 0,
"finished_projects": len(df[df.get('project_status', pd.Series()) == 'FINISHED']) if 'project_status' in df.columns else 0,
"ongoing_projects": len(df[df.get('project_status', pd.Series()) != 'FINISHED']) if 'project_status' in df.columns else 0
}
return summary
def merge_all_datasets(self) -> pd.DataFrame:
"""
Merge sales, rental, and supply data into a single dataset
Returns:
Merged dataframe with all available data
"""
if self.processed_sales_df is None:
self.clean_sales_data()
merged = self.processed_sales_df.copy()
# Merge rental data
if self.processed_rental_df is not None:
rental_cols = ['YEAR', 'AREA_EN', 'MEDIAN_RATE_PER_SQFT', 'RENT_TRANSACTIONS', 'RENT_VALUE']
rental_cols = [col for col in rental_cols if col in self.processed_rental_df.columns]
if rental_cols:
rental_renamed = self.processed_rental_df[rental_cols].copy()
rental_renamed = rental_renamed.rename(columns={
'MEDIAN_RATE_PER_SQFT': 'RENT_MEDIAN_RATE_PER_SQFT',
'RENT_TRANSACTIONS': 'RENTAL_TRANSACTIONS'
})
merged = merged.merge(
rental_renamed,
on=['YEAR', 'AREA_EN'],
how='left'
)
# Add supply summary by area (aggregated)
if self.processed_supply_df is not None:
supply_agg = self.processed_supply_df.groupby('area_name_en').agg({
'no_of_units': 'sum',
'no_of_buildings': 'sum',
'project_status': lambda x: (x == 'FINISHED').sum()
}).reset_index()
supply_agg.columns = ['AREA_EN', 'TOTAL_UNITS', 'TOTAL_BUILDINGS', 'FINISHED_PROJECTS']
supply_agg['AREA_EN'] = supply_agg['AREA_EN'].apply(normalize_area_name)
merged = merged.merge(
supply_agg,
on='AREA_EN',
how='left'
)
return merged
def get_area_supply_data(self, area_name: str) -> Optional[pd.DataFrame]:
"""Get supply data for a specific area (alias for get_supply_by_area)"""
return self.get_supply_by_area(area_name)
def validate_data(self) -> Dict[str, bool]:
"""
Validate all loaded datasets
Returns:
Dictionary with validation results
"""
results = {}
# Validate sales data
if self.sales_df is not None:
required = ['YEAR', 'AREA_EN', 'MEDIAN_RATE_PER_SQFT']
results['sales'] = validate_dataframe(self.sales_df, required)
else:
results['sales'] = False
# Validate rental data
if self.rental_df is not None:
required = ['YEAR', 'AREA_EN', 'MEDIAN_RATE_PER_SQFT']
results['rental'] = validate_dataframe(self.rental_df, required)
else:
results['rental'] = None # Optional
# Validate supply data
if self.supply_df is not None:
required = ['area_name_en'] # Minimal requirement
results['supply'] = validate_dataframe(self.supply_df, required)
else:
results['supply'] = None # Optional
return results
@property
def processed_df(self):
"""Backward compatibility: return processed sales df"""
if self.processed_sales_df is None:
self.clean_sales_data()
return self.processed_sales_df
|