Spaces:
Sleeping
Sleeping
Download data_processor.py from spyronitin890/DUbai: direct link, hf CLI and curl.
- Browser
- Download file 15.4 kB
-
https://huggingface.co/spaces/spyronitin890/DUbai/resolve/main/data_processor.py
- Command line
-
hf download hf://spaces/spyronitin890/DUbai/data_processor.py
-
curl -L -o data_processor.py https://huggingface.co/spaces/spyronitin890/DUbai/resolve/main/data_processor.py
15.4 kB
| """ | |
| 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 | |
| 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 | |