Tabular Cleaning with pandas
Load a messy ticket export with explicit types, then filter, deduplicate, join and aggregate it with pandas into a clean table ready for a RAG corpus.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Load with explicit types
- Step 2: Normalise and filter with boolean masks
- Step 3: Remove duplicates, keeping the latest version
- Step 4: Join account details safely
- Step 5: Aggregate per plan
- Step 6: Write the cleaned corpus
- Troubleshooting
- Check your understanding
- Apply it (stretch)
- Review prompt
Lessons of Data Handling
- JSON, CSV, Parquet and Text Encodings Concept · 15 min
- Round-Tripping Records Safely, CSV Versus Parquet Worked example · 20 min
- Schema Validation with Pydantic Models Lab · 25 min
- Tabular Cleaning with pandas Lab · 25 min
- Check: Clean a Messy Dataset Knowledge check · 6 questions
What you will learn
- Clean and reshape tabular data with pandas: filter, deduplicate, join and aggregate.
Prerequisites: Python Foundations
01. Goal and setup
A per-row schema checks each record on its own. Some problems only show up when you look at the whole table: the same ticket exported twice, a ticket whose account is missing from another table, or a question such as "how many tickets does each plan produce?". That is table work, and pandas is the standard tool for it.
In this lab you will take a messy ticket export and:
- load it with explicit types;
- normalise text and filter out unusable rows with boolean masks;
- remove duplicate tickets, keeping the latest version of each;
- join account details, with a check that the join cannot multiply rows;
- aggregate per plan;
- write the clean table as JSON Lines for the chunking job.
You need Python 3.12 or later (check with python3 --version) and pandas 3. The lab was tested with Python 3.12 and pandas 3.1.1, the version pinned below; the outputs are the same with or without pyarrow installed. Run the steps in order in one session (a notebook with one cell per step, or one script you extend), because each step uses names from the previous ones.
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install "pandas==3.1.1"Save these two files as UTF-8 in your working folder. Ticket 1044 has a body of three spaces, kept in quotes so it survives copying.
ticket_id,account_id,language,created_at,updated_at,text
1042,004217,vi,2024-05-02T09:15:00Z,2024-05-02T10:00:00Z,Không đăng nhập được
1043,000981,FR,2024-05-03T14:40:00Z,2024-05-03T15:00:00Z,Facture en double
1043,000981,fr,2024-05-03T14:40:00Z,2024-05-04T08:30:00Z,Facture en double (réglé)
1044,120554,en,2024-05-03T16:05:00Z,2024-05-03T16:05:00Z," "
1045,004217,en,not recorded,2024-05-04T08:00:00Z,Password reset link expired
1046,120554,en,2024-05-04T09:30:00Z,2024-05-04T09:45:00Z,Export to CSV drops accents
1047,000981,de,2024-05-04T11:00:00Z,2024-05-04T11:10:00Z,Rechnung fehlt
1048,004217, en ,2024-05-05T11:20:00Z,2024-05-05T12:00:00Z,API returns 500 on /search
1049,555000,en,2024-05-05T13:00:00Z,2024-05-05T13:30:00Z,Cannot add a teammate
1050,120554,vi,2024-05-06T07:45:00Z,2024-05-06T08:00:00Z,Lỗi khi xuất hóa đơn
1046,120554,en,2024-05-04T09:30:00Z,2024-05-04T09:45:00Z,Export to CSV drops accents
1051,000981,pt,2024-05-06T10:10:00Z,2024-05-06T10:30:00Z,Não consigo pagar
1052,004217,en,2024-05-07T08:05:00Z,2024-05-07T08:20:00Z,SSO login loops back to sign-in
1053,120554,en,2024-05-07T09:00:00Z,2024-05-07T09:00:00Z,Invoice shows wrong currencyaccount_id,plan,region
004217,enterprise,APAC
000981,team,EU
120554,free,US02. Step 1: Load with explicit types
Read every column as text with dtype="string", then convert the columns you need on purpose. Nothing gets guessed, so account_id keeps its leading zeros in both tables and the join in step 4 compares like with like.
import pandas as pd
raw = pd.read_csv("tickets.csv", dtype="string")
accounts = pd.read_csv("accounts.csv", dtype="string")
tickets = raw.assign(
ticket_id=raw["ticket_id"].astype("int64"),
created_at=pd.to_datetime(raw["created_at"], errors="coerce", utc=True),
updated_at=pd.to_datetime(raw["updated_at"], errors="coerce", utc=True),
)
print(tickets.shape)
print(tickets.dtypes)
print(tickets.loc[tickets["created_at"].isna(), ["ticket_id", "created_at"]])(14, 6)
ticket_id int64
account_id string
language string
created_at datetime64[us, UTC]
updated_at datetime64[us, UTC]
text string
dtype: object
ticket_id created_at
4 1045 NaTThe two conversions fail in opposite ways, on purpose:
astype("int64")raises if anyticket_idis not a whole number. A broken id is a reason to stop and look, not to guess.pd.to_datetime(..., errors="coerce")turns anything it cannot parse intoNaT("not a time"), so one bad date does not stop the load. You can then count and inspect the failures; here only ticket 1045'snot recordedfailed.utc=Truereturns time-zone-aware UTC timestamps.
string is the nullable string dtype, which shows missing values as <NA>. datetime64[us, UTC] means timestamps stored to the microsecond, in UTC. .loc[mask, columns] selects rows by a boolean mask and columns by name in one call. (pandas 2.x prints string[python] and datetime64[ns, UTC]; the values are the same.)
03. Step 2: Normalise and filter with boolean masks
Clean the values first, then decide which rows to keep. The .str accessor applies string methods to every value in a column. Replacing empty strings with pd.NA leaves only one kind of "no text" to test for.
Each condition below is a boolean Series with one True or False per row. Combine them with & (and), | (or) and ~ (not). Python's and and or do not work here: they try to turn a whole Series into a single True or False and raise an error.
tickets["language"] = tickets["language"].str.strip().str.lower()
tickets["text"] = tickets["text"].str.strip().replace("", pd.NA)
has_text = tickets["text"].notna()
has_date = tickets["created_at"].notna()
known_language = tickets["language"].isin(["en", "vi", "fr", "de"])
keep = has_text & has_date & known_language
checks = pd.DataFrame(
{
"ticket_id": tickets["ticket_id"],
"has_text": has_text,
"has_date": has_date,
"known_language": known_language,
}
)
print(checks[~keep])
clean = tickets[keep].copy()
print(len(tickets), "->", len(clean), "rows") ticket_id has_text has_date known_language
3 1044 False True True
4 1045 True False True
11 1051 True True False
14 -> 11 rowsThree tickets go: 1044 has only whitespace, 1045 has no usable date, and 1051 is in Portuguese, which this corpus does not support yet. Printing the failed checks instead of only a count tells you why each row went, which is what you need when someone asks where ticket 1051 is.
Normalising first matters. Without strip().lower(), ticket 1048 (en) and the first copy of 1043 (FR) would also have been dropped as unknown languages. .copy() makes it explicit that clean is a table of its own. pandas 3 always uses copy-on-write, so changing a filtered table never changes the one it came from; on pandas 2.x, the .copy() also avoids the SettingWithCopyWarning that assigning to a filtered table could raise.
04. Step 3: Remove duplicates, keeping the latest version
Exports often contain the same ticket more than once: a re-export, a retry, or an updated version of the ticket. Look before you delete. duplicated(subset="ticket_id", keep=False) marks every row whose id appears more than once.
repeated = clean[clean.duplicated(subset="ticket_id", keep=False)]
print(repeated[["ticket_id", "updated_at", "text"]])
clean = (
clean.sort_values("updated_at")
.drop_duplicates(subset="ticket_id", keep="last")
.sort_values("ticket_id")
.reset_index(drop=True)
)
print(len(clean), "unique tickets")
print(clean.loc[clean["ticket_id"] == 1043, "text"].item()) ticket_id updated_at text
1 1043 2024-05-03 15:00:00+00:00 Facture en double
2 1043 2024-05-04 08:30:00+00:00 Facture en double (réglé)
5 1046 2024-05-04 09:45:00+00:00 Export to CSV drops accents
10 1046 2024-05-04 09:45:00+00:00 Export to CSV drops accents
9 unique tickets
Facture en double (réglé)Ticket 1043 has two versions with different updated_at times; 1046 is an exact copy. Sorting by updated_at and then keeping the last row for each id keeps the newest version of every ticket, so 1043 keeps its resolved text. With the default, keep="first", you would keep the oldest version instead, and the corpus would answer from an out-of-date ticket.
Choose the subset deliberately. Deduplicating on ticket_id treats two versions of a ticket as one; deduplicating on every column would have kept both versions of 1043, because their update times and texts differ. The final sort_values("ticket_id") and reset_index(drop=True) only restore a tidy order and a fresh 0 to 8 index.
05. Step 4: Join account details safely
Bring in each ticket's plan and region with merge. how="left" keeps every ticket, whether or not its account is found. Two more arguments make the join safe:
validate="many_to_one"checks that eachaccount_idappears at most once inaccounts. If not, pandas raisesMergeErrorinstead of quietly repeating tickets once per duplicate account row.indicator=Trueadds a_mergecolumn that records, for each row, whether it found a match:both,left_onlyorright_only.
joined = clean.merge(
accounts, on="account_id", how="left", validate="many_to_one", indicator=True
)
print(len(clean), "->", len(joined), "rows")
print(joined["_merge"].value_counts())
print(joined.loc[joined["_merge"] == "left_only", ["ticket_id", "account_id"]])
broken = pd.concat([accounts, accounts.iloc[[0]]])
try:
clean.merge(broken, on="account_id", how="left", validate="many_to_one")
except pd.errors.MergeError as exc:
print("MergeError:", exc)9 -> 9 rows
_merge
both 8
left_only 1
right_only 0
Name: count, dtype: int64
ticket_id account_id
5 1049 555000
MergeError: Merge keys are not unique in right dataset; not a many-to-one merge
Duplicates in right:
account_id
004217 ...The row count is unchanged, which is what a many-to-one left join must give. Ticket 1049 belongs to account 555000, which is missing from accounts.csv. It stays in the table with empty plan and region, and _merge says so. Decide on purpose what such rows mean (here they will be grouped as unknown) rather than using an inner join that drops them without a trace.
The second merge uses an accounts table in which 004217 appears twice. validate stops it before any ticket is duplicated, and the error message names the repeated key. If that happens with real data, fix or deduplicate the accounts table; do not remove validate to make the error go away.
06. Step 5: Aggregate per plan
groupby("plan") splits the table into one group per plan, and .agg with named aggregations computes several statistics in one pass. Each argument has the form new_column=(source_column, function).
joined["plan"] = joined["plan"].fillna("unknown")
joined["text_chars"] = joined["text"].str.len()
summary = (
joined.groupby("plan")
.agg(
tickets=("ticket_id", "count"),
languages=("language", "nunique"),
median_chars=("text_chars", "median"),
first_seen=("created_at", "min"),
)
.reset_index()
)
print(summary) plan tickets languages median_chars first_seen
0 enterprise 3 2 26.0 2024-05-02 09:15:00+00:00
1 free 3 2 27.0 2024-05-04 09:30:00+00:00
2 team 2 2 19.5 2024-05-03 14:40:00+00:00
3 unknown 1 1 21.0 2024-05-05 13:00:00+00:00For each plan you now have the number of tickets, the number of languages, the median body length and the earliest ticket. Summaries like this are a cheap health check before data reaches the corpus: a plan with no tickets, or a median length of three characters, points to a problem upstream.
fillna("unknown") runs first for a reason. By default groupby leaves out rows whose key is missing (dropna=True), so without it ticket 1049 would vanish from the summary and the counts would no longer add up to 9.
07. Step 6: Write the cleaned corpus
Write the clean table for the chunking job as JSON Lines: one document per line, readable from any language. force_ascii=False keeps the Vietnamese and French text readable (pandas writes the file as UTF-8), and date_unit="s" writes timestamps to the second.
import json
corpus = joined.drop(columns=["_merge", "text_chars"])
corpus.to_json(
"tickets_clean.jsonl",
orient="records",
lines=True,
force_ascii=False,
date_format="iso",
date_unit="s",
)
with open("tickets_clean.jsonl", encoding="utf-8") as f:
lines = f.readlines()
print(len(lines), "documents written")
print(json.dumps(json.loads(lines[0]), indent=2, ensure_ascii=False))9 documents written
{
"ticket_id": 1042,
"account_id": "004217",
"language": "vi",
"created_at": "2024-05-02T09:15:00Z",
"updated_at": "2024-05-02T10:00:00Z",
"text": "Không đăng nhập được",
"plan": "enterprise",
"region": "APAC"
}The account id kept its zeros, the timestamps are ISO 8601 in UTC, and the plan and region came from the join. Fourteen raw rows became nine documents, and you can account for every one that left: three failed the filters, two were duplicates. If the next job filters or aggregates instead of streaming documents, write Parquet instead with corpus.to_parquet("tickets_clean.parquet", index=False) after installing pyarrow.
08. Troubleshooting
09. Check your understanding
10. Apply it (stretch)
Push the lab further:
- Find near-duplicates across different ticket ids: add a column with the lower-cased text with runs of whitespace collapsed, then use
duplicated(subset=[...], keep=False)on that column to list tickets whose text is identical. Decide whether they belong in the corpus twice. - Count tickets per
regionandlanguagewithgroupby(["region", "language"]).size(), then use.unstack(fill_value=0)to see which languages each region needs. - Chain the two labs: validate rows with the Pydantic model first, run this cleaning on the valid rows only, and write the result to both JSON Lines and Parquet.
- Wrap steps 1 to 6 in a function
clean_tickets(tickets_path, accounts_path)and write a test that checks the sample files give 9 rows and oneunknownplan.
11. Review prompt
Without looking back, explain why the lab sorts by updated_at before calling drop_duplicates, why it fills missing plans before grouping, and why it keeps unmatched tickets with a left join instead of using an inner join.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.