Financial TimesAmericas' Fastest-Growing 2025
Certified PartnerOdoo Gold · Adobe Gold Solution · Shopify Premier partnershipsOdoo Gold · Adobe Gold · Shopify Premier partnerSee all
One business dayA senior architect replies to every inquiry · +1 (631) 897-7276Architect reply within one business dayLet's talkCall us
Inc. Regionals 2025Fastest-growing private companies in AmericaInc. Regionals 2025 honoreeSee awards
Americas' Fastest-Growing Companies 2025Recognized by the Financial TimesFT Fastest-Growing Companies 2025See the rankingRanking
4.8 / 5 on Clutch265 verified client reviews4.8/5 on Clutch · 265 reviewsRead the reviews
4.8 · 265 Clutch reviews
US United States
October 9, 202415 min readUpdated on October 19, 2026

Data analytics with Python tutorial: 8 steps on real Census data

· Vice President, Mobility Solutions
Data analytics with Python tutorial: 8 steps on real Census data

Most Python tutorials start with a toy table of five fruit prices. Then you open your first real export. The file won't load, the ID codes have lost their leading zeros and the state totals sit in the same table as the county rows.

This data analytics with Python tutorial works on a file that does all three: the US Census Bureau's county population estimates, released in March 2026. You'll go from an empty folder to four charts and an Excel workbook in 8 steps. Every code block was run on pandas 3.1.0 and Matplotlib 3.11.2 on October 23, 2026. The outputs are pasted from that run, not tidied up afterward.

What you need for this data analytics with Python tutorial

Data analysis with Python means using pandas and a few companion libraries to load data, clean it, summarize it and chart it, all in code you can rerun. A spreadsheet can do much of the same work. The difference is that the fixes live in a script anyone can read, instead of in someone's clicks.

You need basic Python: variables, lists, functions and if statements. If you've written an Excel formula with IF, you're closer than you think. You also need about 2 MB of disk space for the data file and a browser for JupyterLab.

By the end, you'll have read a badly behaved CSV correctly, caught a double-counting trap, run a correlation, reshaped a table and exported the results for Power BI. If you're still deciding whether Python is the right tool, our companion piece covers why teams use it and when to skip it. This page assumes you've decided.

Step 1: Set up your development environment

Install a recent Python first. Python 3.13, 3.14 and 3.15 are all in bugfix support, and 3.15 shipped on October 9, 2026, per the Python release status page. pandas 3.1.0 needs Python 3.11 or later.

Option A: uv (one tool, with a lock file)

uv creates the project, the virtual environment and a lock file in one go. Install it from the uv installation page, then run:

uv init census-analysis
cd census-analysis
uv add pandas matplotlib openpyxl
uv run --with jupyter jupyter lab

The last command is the pattern from uv's Jupyter guide. It opens JupyterLab in your browser with access to the project's packages.

Option B: pip and venv (built into Python)

python3 -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install pandas matplotlib openpyxl jupyterlab
jupyter lab

pip install is the same command everywhere, but the activation path depends on your operating system. On Windows, the script lives in Scripts rather than bin, as the venv documentation explains. Jupyter's own install page gives the same pip install jupyterlab and jupyter lab commands.

Either way, you get an isolated environment, so this project's library versions can't break another one. These are the versions we tested against.

Package What it does here Version tested (Oct 23, 2026)
pandas Reading, cleaning, grouping and exporting tables 3.1.0
NumPy Arrays and mathematical functions under pandas 2.5.4
Matplotlib Charts 3.11.2
openpyxl Writing Excel files from pandas 3.1.5
JupyterLab Interactive notebook interface 4.6.4
uv Environment and package manager (optional) 0.13.5

NumPy installs automatically with pandas. It handles the math library work (vectorized arithmetic, linear algebra, random numbers), and you'll call it directly once in Step 5.

Step 2: Download the dataset and import data with pandas

We'll use the Census Bureau's county population totals for 2020–2025, the Vintage 2025 release. The file is co-est2025-alldata.csv, about 2 MB, with one row per state and county. Its file layout defines all 99 columns: July 1 population estimates for each year, plus births, deaths and migration.

Download it into your project folder. Then, in a new notebook, try the obvious first line:

import pandas as pd

raw = pd.read_csv("co-est2025-alldata.csv")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf1 in position 2: invalid continuation byte

That's your first real-world lesson. pandas assumes UTF-8, but this file is Latin-1 encoded. Byte 0xf1 is the "ñ" in Doña Ana County, New Mexico.

There's a second, quieter problem. Read the file without help, and the state code 01 (Alabama) becomes the number 1. FIPS codes are identifiers, not quantities, so they must stay text. The following code fixes both in the same call:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

raw = pd.read_csv(
    "co-est2025-alldata.csv",
    encoding="latin-1",
    dtype={"SUMLEV": str, "STATE": str, "COUNTY": str},
)
print(raw.shape)
(3195, 99)

pd.read_csv also accepts a URL directly. If that fails with a CERTIFICATE_VERIFY_FAILED error on your machine, download the file in your browser and read the local copy, as we did here.

In your own work, you'll collect data from various sources: database exports, Excel files, APIs. pandas has a function for reading data from each, such as read_sql, read_excel and read_json.

Step 3: Inspect the raw data before you trust it

Look at the data before you calculate anything. Four checks catch most problems in raw data:

raw.info(verbose=False)                # size, data types, memory
print(raw.isna().sum().sum())          # missing values across all columns
print(raw.duplicated().sum())          # fully duplicated rows
print(raw["SUMLEV"].value_counts())    # what kinds of rows are in here?
<class 'pandas.DataFrame'>
RangeIndex: 3195 entries, 0 to 3194
Columns: 99 entries, SUMLEV to RNETMIG2025
dtypes: float64(30), int64(64), str(5)
memory usage: 2.4 MB
0
0
SUMLEV
050    3144
040      51
Name: count, dtype: int64

No missing data and no duplicates is rare. On your own files, isna().sum() per column shows where the gaps are. Then you decide whether to drop those rows with dropna(), fill them with fillna() or flag them for follow-up.

The str in the dtypes line is new. pandas 3 stores text in a dedicated string type instead of the old object type, per the pandas 3.0 release notes. Older tutorials will show object, and both work here.

The SUMLEV count is the line that matters. The layout defines 040 as a state and 050 as a county, so this file mixes two summary levels. Sum the population column as-is and you'll count everyone in America twice. Finance exports do the same thing when subtotal rows sit next to line items. Run raw["STNAME"].nunique() and you get 51: the 50 states plus the District of Columbia.

Step 4: Clean the data and fix column names

Cleaning here means four things: keep only the columns you need, give them readable names, split states from counties and prove the split worked.

years = range(2020, 2026)
cols = ["SUMLEV", "REGION", "STATE", "COUNTY", "STNAME", "CTYNAME"]
cols += [f"POPESTIMATE{y}" for y in years]
cols += ["NATURALCHG2025", "INTERNATIONALMIG2025", "DOMESTICMIG2025"]

df = raw[cols].rename(columns={"STNAME": "state", "CTYNAME": "county"})
df = df.rename(columns={f"POPESTIMATE{y}": f"pop_{y}" for y in years})
df["fips"] = df["STATE"] + df["COUNTY"]

region_names = {1: "Northeast", 2: "Midwest", 3: "South", 4: "West"}
df["region"] = df["REGION"].map(region_names).astype("category")

states = df[df["SUMLEV"] == "040"]
counties = df[df["SUMLEV"] == "050"]

# Validation: counties must add up to their state, exactly
county_sum = counties.groupby("state")["pop_2025"].sum()
state_total = states.set_index("state")["pop_2025"]
assert (county_sum - state_total).abs().max() == 0
assert counties["fips"].is_unique

The first assert is the most important line in this step. If counties and states disagree, the script stops instead of quietly producing a wrong chart. Here they match to the person. The second assert confirms each county ID appears once. Unique identifiers, consistent categories and plausible ranges are the data quality checks worth automating on any file.

Two smaller choices. The layout codes regions 1–4, so mapping them to names makes the output readable, and the category type suits a column with four values. The fips column joins state and county codes into a 5-digit key, such as 35013 for Doña Ana County. It's the standard ID for joining other federal county data later. One exception to plan for: Connecticut's rows are 9 planning regions, not traditional counties, so joins with older county data won't line up there.

If you learned pandas before 2026, you might expect a SettingWithCopyWarning when you add columns to states later. Not anymore. pandas 3 made copy-on-write the only behavior, so a filtered DataFrame acts as its own copy, and the warning is gone, per the release notes.

Step 5: Explore with descriptive statistics

Exploratory analysis is where you generate insights worth checking, not final answers. Start with growth over the five years from July 2020 to July 2025:

states["growth_pct"] = (states["pop_2025"] / states["pop_2020"] - 1) * 100
counties["growth_pct"] = (counties["pop_2025"] / counties["pop_2020"] - 1) * 100

print(states["growth_pct"].describe().round(2))
print(states.nlargest(5, "growth_pct")[["state", "pop_2025", "growth_pct"]].round(1))
count    51.00
mean      2.96
std       2.80
min      -1.42
25%       0.79
50%       2.65
75%       4.64
max       9.76
Name: growth_pct, dtype: float64

               state  pop_2025  growth_pct
565            Idaho   2029733         9.8
331          Florida  23462518         8.7
2358  South Carolina   5570274         8.5
2568           Texas  31709821         8.5
2823            Utah   3538904         7.8

describe() gives you the count, mean, standard deviation and quartiles in one call. The median state grew 2.65%. Idaho grew fastest, and at the bottom, West Virginia (-1.4%), Hawaii (-1.3%) and Louisiana (-0.7%) shrank.

Now use NumPy for a simple example of a conditional label, then filter to large counties so a 300-person county can't top the list:

counties["trend"] = np.where(counties["growth_pct"] < 0, "shrinking", "growing")
print(counties["trend"].value_counts())

big = counties[counties["pop_2025"] >= 250_000]
print(big.nlargest(5, "growth_pct")[["county", "state", "pop_2025", "growth_pct"]].round(1))
growing      1883
shrinking    1261
Name: count, dtype: int64

                 county    state  pop_2025  growth_pct
111        Pinal County  Arizona    539380        25.4
386    St. Johns County  Florida    346328        25.0
2738  Montgomery County    Texas    781194        24.9
2673        Hays County    Texas    304390        24.8
380      Osceola County  Florida    481718        23.2

So 1,261 of 3,144 counties lost population between 2020 and 2025. Among the 294 counties with at least 250,000 people, Pinal County, Arizona, grew fastest. The size filter matters: percentage rankings of small groups are where extreme values live.

Check a relationship: do bigger counties grow faster?

Descriptive statistics describe one variable at a time. To test whether two variables move together, use a correlation and a scatter plot. Here, county size is on a log scale, because populations range from a few hundred to millions:

counties["log_pop_2020"] = np.log10(counties["pop_2020"])
r = counties["log_pop_2020"].corr(counties["growth_pct"])
slope, intercept = np.polyfit(counties["log_pop_2020"], counties["growth_pct"], 1)
print(round(r, 2), round(r**2, 3), round(slope, 2))

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.scatter(counties["log_pop_2020"], counties["growth_pct"], s=6, alpha=0.4)
xs = np.linspace(counties["log_pop_2020"].min(), counties["log_pop_2020"].max(), 50)
ax.plot(xs, slope * xs + intercept, color="black")
ax.set_xlabel("County population in 2020 (log10)")
ax.set_ylabel("Growth 2020 to 2025 (%)")
fig.tight_layout()
fig.savefig("size_vs_growth.png", dpi=150)
0.31 0.093 2.55

The correlation is 0.31: positive, but modest. np.polyfit fits a least-squares line, the same ordinary least squares method behind a linear regression. Its slope says a county 10 times larger grew about 2.6 percentage points more, on average. The R-squared of 0.093 says size explains only about 9% of the variation in growth.

So size matters a little, and something else matters a lot more. That's a typical exploratory result: it tells you where to dig, not what to conclude. Correlation also isn't causation. For formal hypothesis testing, statsmodels reports p-values and confidence intervals, and SciPy's stats module covers common statistical tests.

Everything in this tutorial is descriptive: what happened and where. Forecasting next year's growth is a different job. scikit-learn's LinearRegression fits the same kind of line, but a predictive model also needs a held-out test set and a way to measure its performance. Treat that as its own project.

Step 6: Group, aggregate and reshape

Grouping is where data manipulation turns into answers. This block sums each region's 2025 population and the three parts of its change: natural change (births minus deaths), international migration and domestic migration.

by_region = (
    states.groupby("region", observed=True)
    .agg(
        pop_2025=("pop_2025", "sum"),
        natural_change=("NATURALCHG2025", "sum"),
        international_mig=("INTERNATIONALMIG2025", "sum"),
        domestic_mig=("DOMESTICMIG2025", "sum"),
    )
    .sort_values("pop_2025", ascending=False)
)
print(by_region)
print(by_region["domestic_mig"].sum())
            pop_2025  natural_change  international_mig  domestic_mig
region
South      133833983          222866             596005        357790
West        80146154          190002             239654       -168278
Midwest     69762666           46417             180161         16040
Northeast   58042054           59573             246382       -205552
0

The South holds 133.8 million of the 341.8 million people counted, and it was the only region with a large domestic migration gain in the year to July 2025. The Northeast and the West lost more people to other states than they gained.

The 0 at the bottom is a free sanity check. People who move between states leave one region and arrive in another, so net domestic migration must cancel out nationally. If it didn't, something in your filters would be wrong.

Reshape from wide to long

The file stores one column per year, which is wide format. Most charting and grouping is easier in long format: one row per state per year. melt does the conversion, and pivot_table rolls it back up by region:

long = states.melt(
    id_vars=["state", "region"],
    value_vars=[f"pop_{y}" for y in years],
    var_name="year",
    value_name="population",
)
long["year"] = long["year"].str.removeprefix("pop_").astype(int)

trend = long.pivot_table(index="year", columns="region",
                         values="population", aggfunc="sum", observed=True)
indexed = (trend / trend.loc[2020] * 100).round(1)
print(indexed)
region  Midwest  Northeast  South   West
year
2020      100.0      100.0  100.0  100.0
2021       99.8       99.6  100.7   99.9
2022       99.8       99.5  102.1  100.2
2023      100.2      100.0  103.5  100.7
2024      100.8      100.9  104.9  101.5
2025      101.1      101.1  105.8  101.9

Indexing each region to 2020 = 100 lets you compare growth rates across very different sizes. The South grew 5.8% over five years, while the Midwest and Northeast both dipped below their 2020 level before recovering.

Step 7: Visualize the results with Matplotlib

Data visualization is how analysis reaches people who won't read code. Three charts cover this dataset: a line chart for the trend, a bar chart for the ranking and a box plot for the spread.

# Line chart: regional trend
fig, ax = plt.subplots(figsize=(8, 4.5))
indexed.plot(ax=ax, marker="o")
ax.set_title("US population by Census region (2020 = 100)")
ax.set_xlabel("Estimate as of July 1")
ax.set_ylabel("Index")
fig.tight_layout()
fig.savefig("region_trend.png", dpi=150)

# Bar chart: top 10 states
top10 = states.nlargest(10, "growth_pct").sort_values("growth_pct")
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.barh(top10["state"], top10["growth_pct"])
ax.set_title("Fastest-growing states, July 2020 to July 2025")
ax.set_xlabel("Population growth (%)")
fig.tight_layout()
fig.savefig("top10_states.png", dpi=150)

# Box plot: spread of county growth within each region
fig, ax = plt.subplots(figsize=(8, 4.5))
counties.boxplot(column="growth_pct", by="region", ax=ax, showfliers=False)
fig.suptitle("")
ax.set_title("County growth by region, 2020 to 2025")
ax.set_ylabel("Population growth (%)")
fig.tight_layout()
fig.savefig("county_growth_boxplot.png", dpi=150)

Read the box plot this way: each box spans the middle 50% of counties (the first to third quartile), and the line inside is the median. We hid the outlier dots with showfliers=False to keep the scale readable; drop that argument to see them. If you prefer fewer lines of code, seaborn builds statistical plots such as box plots and correlation heatmaps on top of Matplotlib.

The box plot tells a story the totals hide. Check the medians directly:

print(counties.groupby("region", observed=True)["growth_pct"].median().round(1))
Midwest      0.1
Northeast    0.8
South        2.1
West         2.2
Name: growth_pct, dtype: float64

The South added the most people in total. But the typical Western county grew slightly faster (2.2% against 2.1%), and the Southern box is the widest of the four. A handful of fast-growing large counties pull the Southern total up, yet 499 of the region's 1,422 counties shrank. Those shrinking counties had a median 2025 population of 15,836, against 38,288 for the growing ones. If you only report sums, you'd miss all of that.

Step 8: Export for Excel and Power BI

Your colleagues probably live in Excel or a BI tool. Give them a clean table, not a notebook:

out = states.sort_values("growth_pct", ascending=False)
out.to_csv("state_growth_2020_2025.csv", index=False)

with pd.ExcelWriter("population_summary.xlsx") as writer:
    out.to_excel(writer, sheet_name="States", index=False)
    by_region.to_excel(writer, sheet_name="Regions")

to_excel needs openpyxl, which is why it's in the Step 1 install. Without it, you'll see ModuleNotFoundError: No module named 'openpyxl'.

The CSV loads straight into Power BI. Power BI Desktop can also run Python scripts and import a pandas DataFrame as a data source. If this analysis has to feed a governed dashboard every month, our Power BI consulting team would start by moving the notebook logic into a scheduled pipeline. Then nobody reruns cells by hand.

Make it rerunnable next year

Notebooks are for exploring. Repeat work belongs in a script. Copy the cells from Steps 2–8 into analysis.py and run it:

uv run python analysis.py      # or: python analysis.py inside your venv

When the Census Bureau publishes the next vintage, change the file name and rerun the whole script. Don't append the new year to last year's output. The Bureau revises the entire 2020–2025 series with each release, per the dataset page, so numbers from different vintages shouldn't be mixed. Keep in mind these are estimates, not counts. The assert from Step 4 will tell you if the new file's structure changed.

A few habits keep the script working when someone else runs it:

  • Commit the script and the lock file (uv.lock or a pinned requirements.txt) to Git, so you can see exactly what changed between runs.
  • Write your assumptions down. A comment that says "growth = July 2020 to July 2025, counties only" saves a long meeting later.
  • Break the work into one function per step (load, clean, summarize), which makes each piece testable on its own.
  • Load only what you need. read_csv accepts usecols to skip columns you won't use. pandas is an in-memory tool, so a file near your machine's RAM size needs a different approach. Our companion article covers Polars and DuckDB for that case.
  • Treat private data differently. This file holds public aggregates. With customer or employee records, collect only the fields you need and keep raw files out of shared folders and Git.

In practice, the jump from one analyst's script to a job that runs on a schedule is where most teams stall. When you get there, our Python development team would start with the validation checks, then the scheduling. Tell us what your script does and what it feeds.

The pandas ideas you just used

If pandas is new to you, these six ideas cover nearly everything above.

Idea What it is Example from this tutorial
DataFrame A table with labeled columns and a row index raw, states, counties
Series One column of a DataFrame states["growth_pct"]
Boolean filter Keep rows where a condition is true df[df["SUMLEV"] == "040"]
.loc and .iloc Access individual elements by label or by position raw.loc[1, "CTYNAME"] returns "Autauga County"
groupby().agg() Split rows into groups, then summarize each Population and migration by region
melt and pivot_table Reshape between wide and long formats One row per state per year

Once those feel natural, you can handle most table shapes you'll meet at work, and the rest of the library is mostly vocabulary. The pandas user guide is the place to look things up.

Troubleshooting: common errors and fixes

We reproduced each of these error messages while testing this tutorial.

Error or symptom Cause Fix
UnicodeDecodeError: 'utf-8' codec can't decode File isn't UTF-8 Pass encoding="latin-1" (or the file's real encoding)
IDs lose leading zeros (01 becomes 1) Codes read as numbers Pass dtype={"STATE": str} for ID columns
Totals are double what you expect Summary and detail rows in one file Filter on the summary-level column first
KeyError: 'Population' Column name doesn't exist or has different case Check df.columns and rename early
ModuleNotFoundError Package installed in a different environment Activate the right venv, or use uv run
CERTIFICATE_VERIFY_FAILED reading a URL Local certificate setup Download the file, then read the local copy

FAQ

Why is Python used for data analysis?

Because the analysis becomes code you can rerun, review and put under version control, instead of steps buried in a spreadsheet. pandas covers loading, cleaning, grouping and exporting, and the same language extends into statistics and machine learning. It's also widely used: 58.0% of respondents in the Stack Overflow Developer Survey 2026 used Python, close behind SQL at 58.4%.

Is pandas enough for data analysis?

For most tabular work that fits comfortably in your machine's memory, yes. pandas handles reading, cleaning, grouping, reshaping and exporting. You'll add Matplotlib or another library for charts, scikit-learn for machine learning, and Polars or DuckDB when data outgrows memory.

What's harder, SQL or Python?

SQL is usually the smaller first step because it does one job: querying tables. Python is a general-purpose programming language, so there's more to learn, though data analysis only needs a slice of it. Most analysts end up using both, SQL to pull data out of systems and Python for what comes next.

ShareLinkedInXEmail

Related reading

Script works on your laptop? Get it running on a schedule

Plan my data pipeline