📊 New: Local Government Dashboard Templates — 3 Excel Dashboards for City Analysts Get them for $47 →

How to Use Python pandas for Government Data Cleaning

Share
How to Use Python pandas for Government Data Cleaning

Every government data professional has opened an export and felt the same sinking feeling. Dates stored as text. Account numbers with leading zeros stripped by Excel. Department names spelled four different ways. Dollar amounts with commas, parentheses, and the occasional “N/A” sitting in a numeric column. The analysis you planned to do in an hour now needs three hours of cleanup first.

Government data is messy for structural reasons. It comes from billing platforms, ERP systems, call center applications, work order trackers, and spreadsheets maintained by different people over many years. Each system has its own conventions, and none were designed to talk to each other. Cleaning that data is the unglamorous foundation under every dashboard, KPI report, and compliance filing.

This guide shows how to do that cleaning in Python with pandas: repeatable, documented, and fast. If you are new to pandas, start with our Python for urban data analysis beginner’s guide, which covers loading files and basic DataFrame operations. This article picks up from there.


Why Clean in Python Instead of Excel?

Excel can clean data. The problem is that Excel cleaning is manual, invisible, and unrepeatable. When you fix 400 inconsistent department names by hand, nobody, including you next month, can see exactly what you changed. When the next export arrives with the same problems, you start over.

A pandas cleaning script solves three problems at once.

It is repeatable. Run the same script on next month’s export and get the same cleaning applied, with no manual steps to forget.

It is documented. The script is a written record of every transformation. When an auditor or a director asks how a number was produced, you can show them.

It scales. A 500,000-row billing export that freezes Excel cleans in seconds.

This matters most in data migration and conversion work, where you move records from one system to another and must prove that nothing was lost or corrupted along the way. A script that logs what it changed is far easier to defend than a series of manual edits.


A Note on pandas 3.0

pandas 3.0, released in January 2026, made two changes that affect cleaning code.

Strings now have their own dtype. Text columns are inferred as a dedicated str type instead of the old catch-all objecttype. For most cleaning work this is invisible, but code that checks whether a column’s dtype equals object to find text columns will need updating.

Copy-on-Write is now the only mode. Any subset or result you create behaves as an independent copy. The practical effect is that chained assignment, such as df["amount"][df["status"] == "Paid"] = 0, no longer modifies your DataFrame. Use .loc to do the selection and assignment in one step instead:

python

df.loc[df["status"] == "Paid", "amount"] = 0

Every example below is written to work on pandas 3.0 and on recent 2.x versions. If you are not sure which version you have, run print(pd.__version__).


Step 1: Load the Data and Look Before You Clean

Never clean blind. Spend two minutes understanding what you have first.

python

import pandas as pd

df = pd.read_csv('billing_export.csv', dtype=str)

print(df.shape)
print(df.head())
print(df.info())
print(df.isna().sum())

Notice dtype=str. Loading every column as text prevents pandas from guessing types and silently damaging your data. An account number like 00123456 stays intact instead of becoming 123456. You convert each column deliberately later, once you have seen what is in it.

The isna().sum() line shows how many missing values each column has. A column that is 40 percent empty tells you something important before you write any other code.


Step 2: Standardize Column Names

Exports often arrive with column headers like Acct #, Amount Billed ($), or Days Past Due , with a trailing space that causes baffling errors later. Standardize them first:

python

df.columns = (
    df.columns
    .str.strip()
    .str.lower()
    .str.replace(r'[^a-z0-9]+', '_', regex=True)
    .str.strip('_')
)

Amount Billed ($) becomes amount_billed. Acct # becomes acct. Every column name is now lowercase, free of spaces and symbols, and safe to use in code.


Step 3: Clean Text Fields

Text inconsistency is the most common government data problem. The same department appears as “Public Works”, “public works”, “PUBLIC WORKS “, and “Pub Works”.

python

text_cols = ['department', 'account_status', 'request_type']

for col in text_cols:
    df[col] = df[col].str.strip().str.title()

That handles case and whitespace. For genuine variations in wording, use an explicit mapping:

python

dept_map = {
    'Pub Works': 'Public Works',
    'Public Wks': 'Public Works',
    'Water & Sewer': 'Water and Sewer',
    'Water/Sewer': 'Water and Sewer',
}

df['department'] = df['department'].replace(dept_map)

The mapping dictionary doubles as documentation. Anyone reading your script can see exactly which variations you consolidated, and you can add new ones as they appear.

Check your work. After cleaning a categorical column, list its unique values and confirm it contains only what you expect:

python

print(df['department'].value_counts(dropna=False))

If an unexpected value appears, you have found a variation your mapping missed.


Step 4: Convert Numbers and Currency

Financial exports regularly store amounts as text with dollar signs, commas, and parentheses for negatives. Strip the formatting, then convert:

python

def clean_currency(series):
    cleaned = (
        series
        .str.replace(r'[\$,]', '', regex=True)
        .str.replace(r'^\((.*)\)$', r'-\1', regex=True)
        .str.strip()
    )
    return pd.to_numeric(cleaned, errors='coerce')

df['amount_billed'] = clean_currency(df['amount_billed'])
df['amount_paid'] = clean_currency(df['amount_paid'])

The second replacement handles accounting notation: (250.00) becomes -250.00.

The errors='coerce' argument is a deliberate choice. Instead of crashing on a bad value like “N/A”, pandas converts it to a missing value. That keeps the script running, but silent failures are dangerous, so always count what was lost:

python

bad_amounts = df['amount_billed'].isna().sum()
print(f'Amounts that could not be converted: {bad_amounts}')

If that number is higher than expected, investigate before moving on.


Step 5: Fix Dates

Dates arrive in every format imaginable, and a column can contain several at once. Convert with an explicit format when you know it:

python

df['bill_date'] = pd.to_datetime(
    df['bill_date'], format='%m/%d/%Y', errors='coerce'
)

When you do not know the format, or it varies, let pandas infer it, but check the result for failures:

python

df['payment_date'] = pd.to_datetime(df['payment_date'], errors='coerce')
print(df['payment_date'].isna().sum(), 'dates could not be parsed')

Watch for dates that parse correctly but are impossible: a bill date in the year 1900, or a completion date earlier than the submission date. Those are data entry errors, and a simple filter will surface them:

python

bad_dates = df[df['payment_date'] < df['bill_date']]
print(len(bad_dates), 'records with payment before billing')

Step 6: Handle Missing Values Deliberately

There is no universal right answer for missing data. The correct treatment depends on what the field means. Government data adds a wrinkle: blank often means something specific, not “unknown.”

A blank payment date on a delinquent account means “not paid yet.” Filling it with a made-up date would corrupt your analysis. A blank turn-off field on a stormwater-only account means “not applicable.” Those are different situations that should be handled differently.

python

# Blank payment amount on unpaid accounts means zero collected
df['amount_paid'] = df['amount_paid'].fillna(0)

# Mark stormwater accounts explicitly instead of leaving blanks
df.loc[df['account_type'] == 'Stormwater Only', 'turn_off_executed'] = 'N/A'

# Flag, rather than fill, fields you cannot safely assume
df['missing_account_id'] = df['account_id'].isna()

The principle: fill a value only when you know what it should be. When you do not, flag it and let a human decide. A visible gap is always better than an invisible wrong answer.


Step 7: Remove Duplicates Carefully

Duplicate records inflate counts and revenue totals. But deleting rows blindly is risky, because two rows that look similar may be genuinely different events, such as two payments on the same account on the same day.

First, look at what pandas considers a duplicate:

python

dupes = df[df.duplicated(subset=['account_id', 'bill_date'], keep=False)]
print(len(dupes), 'rows involved in duplicate account and date combinations')
print(dupes.sort_values(['account_id', 'bill_date']).head(20))

Read the output. If the duplicates are true copies, remove them:

python

before = len(df)
df = df.drop_duplicates(subset=['account_id', 'bill_date'], keep='first')
print(f'Removed {before - len(df)} duplicate rows')

Always print how many rows you removed. That number belongs in your documentation.


Step 8: Validate Before You Trust It

The last cleaning step is the one most people skip: proving the result is sound. A short block of validation checks catches problems before they reach a dashboard or a council report.

python

checks = {
    'No negative billed amounts': (df['amount_billed'] >= 0).all(),
    'No paid amount exceeds billed': (df['amount_paid'] <= df['amount_billed']).all(),
    'All account IDs present': df['account_id'].notna().all(),
    'Statuses are valid': df['account_status'].isin(
        ['Current', 'Past Due', 'Delinquent', 'Payment Arrangement',
         'Hardship', 'Turned Off']
    ).all(),
}

for name, passed in checks.items():
    print(('PASS  ' if passed else 'FAIL  ') + name)

A failed check does not always mean your cleaning is wrong. Sometimes it reveals a real problem in the source system, which is valuable in its own right. A record showing a payment larger than the bill may be an overpayment or credit that billing staff should review.


Step 9: Export and Keep a Cleaning Log

Save the cleaned data, and record what the script did:

python

df.to_csv('billing_cleaned.csv', index=False)

with open('cleaning_log.txt', 'w') as log:
    log.write(f'Rows loaded: {before}\n')
    log.write(f'Rows after cleaning: {len(df)}\n')
    log.write(f'Amounts that could not be converted: {bad_amounts}\n')

Keep your original export untouched, always. Cleaning should read from the raw file and write a new one, so you can rerun from the beginning at any time.

Once you have a script like this working, it becomes the first stage of an automated reporting pipeline. Our guide to automating monthly government reports with Python shows how to take cleaned exports from several systems and combine them into a formatted leadership report.


Cleaning for Data Migration

Migration projects, moving records from a legacy system into a new platform, raise the stakes. The new system’s import rules are strict, and bad data that a human could tolerate in a spreadsheet will be rejected or, worse, accepted and corrupted.

Three practices make pandas especially valuable in migration work.

Reconcile before and after. Compare record counts and control totals, such as total billed amount, between the source extract and the cleaned file. If the totals do not match and you cannot explain the difference, do not load the data.

Preserve identifiers exactly. Account numbers, parcel IDs, and meter IDs often contain leading zeros or mixed letters and numbers. Load them as text, never as numbers, and never alter them.

Keep an exceptions file. Instead of deleting records that fail validation, write them to a separate file with the reason. Business staff can review and correct them, and nothing disappears without a trace.


Where Cleaning Fits in the Larger Workflow

Cleaning is the first stage of a pipeline that ends with a decision. Python cleans and prepares the data. A dashboard presents it. As covered in our guide to PowerBI vs Excel for local government, the right presentation tool depends on your audience, but every one of them produces better results from data that has been cleaned consistently.

The same applies to the datasets used in our guides to utility billing KPIs and public works KPIs. Every metric in those articles depends on clean status fields, valid dates, and consistent categories. A collection rate calculated from a column containing both “Delinquent” and “delinquent “ will quietly undercount, and nobody will know.


Final Thoughts

Data cleaning is not the exciting part of analytics, but it is where most of the real work happens, and where most errors originate. A script that standardizes text, converts numbers and dates safely, handles missing values deliberately, removes duplicates carefully, and validates its own output turns an hours-long manual chore into a repeatable process you can trust and defend.

Start small. Pick the export you clean by hand most often. Write the script one step at a time, checking the output after each step. By the third month you will have a reusable tool, and a record of exactly how your numbers are produced.

Want a dashboard ready for your cleaned data?

Once your data is clean, the Local Government Dashboard Template Pack gives you three ready-built Excel dashboards for call center, utility billing, and public works reporting. Paste in your cleaned export and the dashboard updates automatically.

Get the Template Pack — $47 →

Read more