Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Excel to Pandas Transition (Zillow Dataset) - Basic

In this introductory notebook, you’ll work with real Zillow housing data, including metro-level home values (ZHVI) and rent estimates (ZORI). We’ll focus on the core Excel-to-Pandas workflow so you can confidently load, inspect, reshape, and analyze the data step by step.

After completing this Basic notebook, continue to Excel_to_Pandas_Zillow_Advanced.ipynb for deeper analysis patterns, richer transformations, and more advanced visualizations.


Professor: Khai Lu
Developer: Rinrada Maneenop
Estimated Time: ~20 minutes


Contents:

  • Introduction: Why Transition from Excel to Pandas?

  • Setting Up: Loading Real Zillow Data

    • Understanding the Wide Format

    • Reshaping with pd.melt() — Excel’s “Unpivot”

  • Basic Data Operations

    • Reading Data

    • Viewing and Inspecting Data

  • Excel Functions Translated to Pandas

    • VLOOKUP/XLOOKUP -> merge() and map()

    • FILTER -> Boolean Indexing

    • SUMIF/COUNTIF -> Conditional Aggregations

    • IF Statements -> np.where() and apply()

Please run the cell below to import all the necessary libraries so your notebook can run without issues!
NOTE: DO NOT edit the cell below, please only run it.

Introduction: Why Transition from Excel to Pandas?

Excel is a powerful tool for data analysis, but it has limitations:

  • Scale: Excel struggles with datasets larger than ~1 million rows

  • Reproducibility: Manual operations are hard to document and reproduce

  • Automation: Repetitive tasks require VBA or manual effort

  • Version Control: Tracking changes is difficult

Pandas, a Python library, addresses these issues:

  • Handles millions of rows efficiently

  • All operations are code-based and reproducible

  • Easy to automate workflows

  • Integrates with version control systems (Git)

  • Free and open-source

In this notebook, you’ll learn how to translate your Excel skills into Pandas using real housing market data from Zillow Research!

Key Concept: DataFrames vs Spreadsheets

In Excel, you work with worksheets containing cells organized in rows and columns.

In Pandas, you work with DataFrames — similar structure but with powerful programmatic capabilities:

Excel ConceptPandas Equivalent
WorkbookMultiple DataFrames
WorksheetDataFrame
ColumnSeries (df['column_name'])
RowRow (df.loc[row_index])
CellSingle value (df.loc[row, col])

Setting Up: Loading Real Zillow Data

We’ll work with two real datasets published by Zillow Research:

  1. home_values (Zillow Home Value Index) — the typical home value by metro area, monthly, going back to 2000

  2. home_values (Zillow Observed Rent Index) — the typical observed rent by metro area, monthly

These are the same datasets analysts at real estate firms and banks use for housing market research.

Load Zillow Home Value Index (home_values)

  • Excel: File → Open → Browse → select the CSV

  • Pandas: use pd.read_csv() with a URL or file path

  • Also load the rent_values rent dataset for the same metros

💡 Understanding the ‘Wide’ Format

The Zillow CSV is in wide format — each date is its own column. This is common in Excel:

RegionName2000-01-312000-02-292000-03-31...
Los Angeles, CA210,000212,000214,000...
New York, NY350,000351,000353,000...

For most pandas analysis, we need long format — each row is one observation (metro + date + value):

RegionNameDateHomeValue
Los Angeles, CA2000-01-31210,000
Los Angeles, CA2000-02-29212,000
New York, NY2000-01-31350,000

Excel Equivalent: Data → Get & Transform → Unpivot Columns
Pandas Equivalent: pd.melt()

Excel ‘Unpivot’ → pd.melt()

  • In Excel: Data → Get & Transform → Unpivot Columns

  • In pandas: use pd.melt to reshape wide date columns into rows

  • Keep metadata columns as identifiers and unpivot the date columns

Column definitions (long-format data)

home_values (Zillow Home Value Index, one row per metro per month):

  • RegionID — Zillow’s unique numeric ID for the region.

  • SizeRank — Rank by market size (0 = largest, e.g. United States or New York; higher = smaller market).

  • RegionName — Name of the metro or area (e.g. “New York, NY”, “Los Angeles, CA”).

  • RegionType — Geography type: country (e.g. United States), or msa = Metropolitan Statistical Area (a core city plus surrounding counties the U.S. government groups as one economic region; “metro” in the data means MSA).

  • StateName — State code (e.g. NY, CA); missing for U.S. or non-state regions.

  • Date — Month of the observation (month-end date).

  • HomeValue — Typical home value in dollars (ZHVI, smoothed, seasonally adjusted, mid-tier).

rent_values (Zillow Observed Rent Index, one row per metro per month):

  • RegionID — Zillow’s unique numeric ID for the region.

  • SizeRank — Rank by market size (0 = largest).

  • RegionName — Name of the metro or area.

  • RegionType — Geography type: country or msa (Metropolitan Statistical Area; see above).

  • StateName — State code; missing for U.S. or non-state regions.

  • Date — Month of the observation.

  • Rent — Typical observed monthly rent in dollars (ZORI, smoothed).


Basic Data Operations

Reading and Inspecting Data

In Excel, you open a file by clicking it. In Pandas, you use read_csv().

Excel: File → Open → Browse → Select file
Pandas: df = pd.read_csv('filename.csv') or df = pd.read_csv('https://...')

Essential Inspection Methods

Excel ActionPandas MethodPurpose
Scroll to see datadf.head() or df.tail()View first/last rows
Ctrl+Down to see sizedf.shapeGet (rows, columns)
Right-click column headerdf.info()See column types and non-null counts
Select column → look at status bardf.describe()Get summary statistics

Excel Functions Translated to Pandas

1. VLOOKUP / XLOOKUP → merge() and map()

VLOOKUP looks up a value in one table and pulls a column from another table.

Excel Formula: =VLOOKUP(RegionName, RentTable, RentColumn, FALSE)

Pandas Equivalent: df.merge() — joins two DataFrames like a SQL JOIN

We’ll use this to attach rent data (rent_values) to home value data (home_values) for the same metro areas.

Using map() as a simpler VLOOKUP

  • Goal: build a dictionary from RegionName to latest HomeValue

  • Use .map() to attach that lookup value to each row

  • Equivalent to an Excel VLOOKUP returning a single column

Using merge() as a full VLOOKUP

  • Goal: combine latest home values and rents for each metro

  • Start from home_values (home values) and join rent_values (rents) on RegionName

  • Keep all metros from home_values and fill missing rents with NaN

💡 map() vs merge() — When to Use Which?

SituationUse
You need ONE value from a lookup tablemap()
You need MULTIPLE columns from another tablemerge()
You want SQL-style join behavior (inner, outer, left)merge()
Fastest option for a simple single-column lookupmap()

2. FILTER → Boolean Indexing

FILTER in Excel (or AutoFilter) selects rows that meet a condition.

Excel: Data → Filter → select criteria
Pandas: df[condition] — called Boolean Indexing

Simple filter: California metros only

  • Excel: AutoFilter on StateName = 'CA'

  • Pandas: subset rows where StateName equals 'CA'

  • Then sort metros by HomeValue descending

Multi-condition filters

  • AND condition: CA metros with HomeValue > 800000

  • OR condition: metros in TX or FL

  • Use & and | with boolean expressions in pandas

Filtering for multiple values with isin()

  • Mimic Excel’s AutoFilter with multiple checked states

  • Define a list of target states like CA, NY, TX, FL, WA

  • Use df['StateName'].isin(target_states) to select matching rows


3. SUMIF / COUNTIF → Conditional Aggregations

SUMIF and COUNTIF calculate totals or counts based on conditions.

Excel Formula: =AVERAGEIF(StateName, "CA", HomeValue)
Pandas Equivalent: Filter then aggregate, or use groupby()

SUMIF / COUNTIF equivalents

  • AVERAGEIF: compute average HomeValue for California metros

  • COUNTIF: count how many metros there are in each state

  • Use filtering plus .mean() and value_counts() in pandas

groupby() as multi-state SUMIF/AVERAGEIF

  • Aggregate HomeValue by StateName in one step

  • Compute median, mean, count, and max per state

  • Excel equivalent would require separate SUMIF/AVERAGEIF formulas for each state

Time-based aggregation: national home value by year

  • Add a Year column derived from the Date

  • Use groupby('Year') and an aggregation like median

  • Excel equivalent: AVERAGEIFS with a year criterion


4. IF Statements → np.where() and apply()

Excel’s IF function creates conditional logic in new columns.

Excel Formula: =IF(HomeValue > 500000, "Expensive", "Affordable")
Pandas Equivalent: np.where() or apply()

Simple IF classification

  • Excel: =IF(HomeValue > 500000, "Expensive", "Affordable")

  • Pandas: use np.where to assign “Expensive” or “Affordable” labels

  • Creates an Affordability column based on HomeValue

Nested IF logic for market tiers

  • Excel example: IF(HomeValue>1000000, "Ultra-Luxury", IF(HomeValue>600000, "Luxury", ...))

  • In pandas, write a helper function and apply it to HomeValue

  • Produces categorical labels like Ultra-Luxury, Luxury, Mid-Range, Affordable

np.select() for multi-level conditions

  • Use multiple boolean conditions and matching labels

  • Cleaner than deeply nested np.where calls

  • Similar to Excel’s IFS() with several thresholds


Quick Reference Cheat Sheet

Excel FunctionPandas EquivalentZillow Example
File → Open CSVpd.read_csv(url)pd.read_csv(home_values_URL)
Data → Unpivotpd.melt()Wide home_values → long format
AutoFilterBoolean indexingdf[df['StateName'] == 'CA']
FILTER (multi-value).isin()df[df['StateName'].isin(['CA','NY'])]
VLOOKUP (1 col)series.map(dict)Map RegionName → latest home value
VLOOKUP / XLOOKUPdf.merge()Join home values + rents by RegionName
SUMIFgroupby().sum()Total value by state
AVERAGEIFgroupby().mean()Avg home value by state
COUNTIFvalue_counts() / groupby().size()Count metros per state
IFnp.where()Classify Affordable vs Expensive
Nested IFSnp.select()Market tier classification
IF (complex).apply(func)Custom category logic
YEAR(Date) + summary.dt.year + groupby()Annual median home value
AVERAGE.mean()National median/mean home value snapshot
MAX/MIN.max() / .min()Most/least expensive metro