File size: 5,740 Bytes
a289188 8625b3d a289188 8625b3d a289188 8625b3d a289188 8625b3d a289188 8625b3d a289188 8625b3d a289188 8625b3d a289188 8625b3d a289188 8625b3d a289188 8625b3d a289188 8625b3d a289188 8625b3d a289188 8625b3d a289188 8625b3d a289188 8625b3d a289188 8625b3d a289188 | 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 | {% extends "base.html" %}
{% block title %}Python Wrangling - Data Science Lab{% endblock %}
{% block content %}
<div class="page-header">
<h1>π Python Data Wrangling</h1>
<p class="breadcrumb">Home / Python Wrangling β Pandas & NumPy for data manipulation</p>
</div>
<div class="concept-section">
<div class="concept-header"><h3>π NumPy β Numerical Computing Foundation</h3></div>
<div class="concept-body">
<p>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.</p>
<h4>π― the region Example: housing Price Analysis with NumPy</h4>
<div class="code-block"><span class="lang-label">Python</span><pre>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}")</pre></div>
<div class="output-display">Mean: $492,000
Std: $138,744
Min PSM: $4,403/sqm
Max PSM: $6,739/sqm
Area-Price correlation: 0.9147</div>
</div>
</div>
<div class="concept-section">
<div class="concept-header"><h3>π Pandas β Data Analysis Powerhouse</h3></div>
<div class="concept-body">
<p>Pandas provides DataFrames for structured data manipulation. Think of it as "Excel for programmers" β but much more powerful.</p>
<h4>π― Loading and Exploring housing Data</h4>
<div class="code-block"><span class="lang-label">Python</span><pre>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))</pre></div>
{% if demo_data %}
<h4>π Live Data Preview</h4>
<div style="overflow-x: auto;">{{ demo_data.head|safe }}</div>
<h4>π Data Shape</h4>
<p>Rows: {{ demo_data.shape[0] }}, Columns: {{ demo_data.shape[1] }}</p>
<h4>π Statistical Summary</h4>
<div style="overflow-x: auto;">{{ demo_data.describe|safe }}</div>
<h4>π Null Counts</h4>
<div class="output-display">{% for col, cnt in demo_data.null_counts.items() %}{{ col }}: {{ cnt }}
{% endfor %}</div>
{% endif %}
<h4>π§ Data Transformation Pipeline</h4>
<div class="code-block"><span class="lang-label">Python</span><pre># 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)</pre></div>
</div>
</div>
<div class="mistakes-box">
<h5>β οΈ Common Mistakes</h5>
<ul>
<li><strong>Chained indexing:</strong> `df[condition]['col'] = val` causes SettingWithCopyWarning. Use `.loc[]` instead.</li>
<li><strong>Ignoring dtypes:</strong> Numeric columns loaded as strings β always check with `.dtypes`</li>
<li><strong>Memory waste:</strong> Use `category` dtype for columns with few unique values (e.g., property_type)</li>
<li><strong>Loop anti-pattern:</strong> Using `for` loops on DataFrames instead of vectorized operations</li>
</ul>
</div>
<div class="exercise-box">
<h5>π§ͺ Try It Yourself</h5>
<p>1. Load the housing data and find the most expensive flat in each town.</p>
<p>2. Create a new column calculating the building age (2024 - lease_commence_date).</p>
<p>3. Use groupby to find the average price per square meter by flat type.</p>
<p>4. Create a pivot table showing average prices by town and flat type.</p>
</div>
{% endblock %}
|