{% extends "base.html" %} {% block title %}Python Wrangling - Data Science Lab{% endblock %} {% block content %}

๐Ÿ“– NumPy โ€” Numerical Computing Foundation

NumPy provides fast, vectorized operations on arrays. It's the backbone of scientific computing in Python, powering Pandas, scikit-learn, and TensorFlow under the hood.

๐ŸŽฏ the region Example: housing Price Analysis with NumPy

Python
import numpy as np

# property prices for different towns
prices = np.array([308000, 430000, 560000, 295000, 468000, 545000, 620000, 710000])
areas = np.array([68, 91, 121, 67, 93, 122, 92, 119])

# Vectorized operations (no loops needed!)
price_per_sqm = prices / areas          # Element-wise division
mean_price = np.mean(prices)            # $492,000
std_price = np.std(prices)              # Spread of prices
above_avg = prices[prices > mean_price] # Boolean indexing

# Statistical summary
print(f"Mean: ${mean_price:,.0f}")       # Mean: $492,000
print(f"Std: ${std_price:,.0f}")         # Std: $138,744
print(f"Min PSM: ${np.min(price_per_sqm):,.0f}/sqm")
print(f"Max PSM: ${np.max(price_per_sqm):,.0f}/sqm")

# Matrix operations for feature engineering
features = np.column_stack([areas, price_per_sqm])
correlation = np.corrcoef(areas, prices)  # Correlation matrix
print(f"Area-Price correlation: {correlation[0,1]:.4f}")
Mean: $492,000 Std: $138,744 Min PSM: $4,403/sqm Max PSM: $6,739/sqm Area-Price correlation: 0.9147

๐Ÿ“– Pandas โ€” Data Analysis Powerhouse

Pandas provides DataFrames for structured data manipulation. Think of it as "Excel for programmers" โ€” but much more powerful.

๐ŸŽฏ Loading and Exploring housing Data

Python
import pandas as pd

# Load CSV data
df = pd.read_csv('data/housing_data.csv')

# Quick exploration
print(df.shape)              # (70, 11) โ€” rows, columns
print(df.dtypes)             # Data types for each column
print(df.describe())         # Statistical summary
print(df.isnull().sum())     # Check for missing values
print(df.head())             # First 5 rows

# Data cleaning pipeline
df['price'] = pd.to_numeric(df['price'], errors='coerce')
df['month_dt'] = pd.to_datetime(df['month'], format='%Y-%m')
df['year'] = df['month_dt'].dt.year
df['price_per_sqm'] = (df['price'] / df['area']).round(2)

# Group-by analysis
town_summary = df.groupby('town').agg(
    avg_price=('price', 'mean'),
    count=('price', 'count'),
    avg_area=('area', 'mean')
).round(0).sort_values('avg_price', ascending=False)

print(town_summary.head(10))
{% if demo_data %}

๐Ÿ“‹ Live Data Preview

{{ demo_data.head|safe }}

๐Ÿ“Š Data Shape

Rows: {{ demo_data.shape[0] }}, Columns: {{ demo_data.shape[1] }}

๐Ÿ“ˆ Statistical Summary

{{ demo_data.describe|safe }}

๐Ÿ” Null Counts

{% for col, cnt in demo_data.null_counts.items() %}{{ col }}: {{ cnt }} {% endfor %}
{% endif %}

๐Ÿ”ง Data Transformation Pipeline

Python
# Method chaining for clean transformation pipeline
result = (
    df
    .dropna(subset=['price'])              # Remove null prices
    .assign(
        price_per_sqm=lambda x: x['price'] / x['area'],
        is_mature=lambda x: x['town'].isin(['DOWNTOWN', 'TOA PAYOH', 'HILLVIEW',
                                             'QUEENSTOWN', 'BUKIT MERAH']),
        price_band=lambda x: pd.cut(x['price'],
                                     bins=[0, 400000, 600000, 800000, float('inf')],
                                     labels=['Budget', 'Mid', 'Premium', 'Luxury'])
    )
    .query('price > 0')                     # Filter valid prices
    .sort_values('price', ascending=False)   # Sort by price
)

# Pivot table
pivot = df.pivot_table(
    values='price',
    index='town',
    columns='property_type',
    aggfunc='mean'
).round(0)

print(pivot)
โš ๏ธ Common Mistakes
๐Ÿงช Try It Yourself

1. Load the housing data and find the most expensive flat in each town.

2. Create a new column calculating the building age (2024 - lease_commence_date).

3. Use groupby to find the average price per square meter by flat type.

4. Create a pivot table showing average prices by town and flat type.

{% endblock %}