Skip to content
D-CSIL™

AI Guide · 2026-11-22 · 1:01 PM CT

Clean a messy CSV in six steps with pandas

Paul Derrington, Jr.

By Paul Derrington, Jr.

CEO | Chief Engineer | Research Engineer | Editor, D-CSIL

3 min read

Follow @PaulDerrington on X

Key Takeaways

A messy CSV is not an analysis problem yet. It is a cleanup problem. This guide loads a file with pandas, fixes types and missing values, removes duplicates, groups the result, and saves a clean copy — every step checked against the pandas documentation and run on a test file.

Steps 1-2: Load it, then look before you touch anything

Step 1 — Install and load. Run: pip install pandas. Then in Python: import pandas as pd, followed by df = pd.read_csv('your-file.csv'). The pandas I/O guide lists read_csv as the workhorse for text files and to_csv as its matching writer, so the same pair loads and later saves the file.

Step 2 — Inspect. Run df.head(), df.shape, df.dtypes and df.isna().sum() before changing anything. That shows the first rows, the row and column count, the type pandas guessed for each column, and how many missing values each column holds. Write those numbers down: they are your check that cleanup did not silently lose rows.

Steps 3-4: Fix types and missing values on purpose

Step 3 — Fix types. Text columns with stray spaces break grouping, so trim them: df['item'] = df['item'].str.strip(). Convert dates with df['date'] = pd.to_datetime(df['date'], errors='coerce') and numbers with df['amount'] = pd.to_numeric(df['amount'], errors='coerce'). The errors='coerce' setting turns unparseable values into missing markers instead of crashing, so you can count and handle them. The pandas I/O guide recommends applying to_datetime after reading when date formats are complex.

Step 4 — Decide on missing values, do not just delete them. The pandas missing-data guide is clear that detection uses isna() or notna(), and that missing values propagate through calculations. Drop rows only where a missing value kills the record — for example df = df.dropna(subset=['date']) — and fill or leave the rest deliberately. Re-run df.isna().sum() so the change is a decision you can see, not a side effect.

Steps 5-6: Remove duplicates, group, and save a clean copy

Step 5 — Remove exact duplicates with df = df.drop_duplicates(), then group: totals = df.groupby('item')['amount'].sum(). The pandas groupby guide describes this as split-apply-combine: split rows into groups, apply a function such as sum to each group, and combine the results. Check the grouped totals against a hand count on a few rows before trusting them.

Step 6 — Save the clean file under a new name: df.to_csv('clean.csv', index=False). Never overwrite the raw file. Compare the new df.shape with the shape from Step 2 and account for every row you removed — duplicates and dropped missing-date rows should explain the difference exactly.

Where this stops working

This workflow handles one flat file with consistent columns. It does not fix merged header rows, files where one column mixes dates and text by design, or duplicates that differ by a typo — those need a key column and a drop_duplicates(subset=[...]) call, or manual review. If an AI assistant wrote any of this code for you, run it on a small copy first and check the row counts at each step; generated code that runs is not the same as code that cleaned the right rows.

Disclaimer: Derrington Collaborative AI is my personal business, operated independently of and outside my official U.S. Government position and duties. The views and opinions expressed on this site and on any and all of my social media accounts are my own. They do not reflect the official policy or position of the Department of the Army, the Department of Defense, or the U.S. Government. Mention of any company, product, or service does not constitute an official endorsement.