Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 5 · Lab · 25 min · revision 2

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

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:

  1. load it with explicit types;
  2. normalise text and filter out unusable rows with boolean masks;
  3. remove duplicate tickets, keeping the latest version of each;
  4. join account details, with a check that the join cannot multiply rows;
  5. aggregate per plan;
  6. 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.

Create an environment and install pandas
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.

tickets.csv
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 currency
accounts.csv
account_id,plan,region
004217,enterprise,APAC
000981,team,EU
120554,free,US

02. 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.

Step 1
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"]])
Expected output
(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        NaT

The two conversions fail in opposite ways, on purpose:

  • astype("int64") raises if any ticket_id is 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 into NaT ("not a time"), so one bad date does not stop the load. You can then count and inspect the failures; here only ticket 1045's not recorded failed. utc=True returns 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.

Step 2
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")
Expected output
    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 rows

Three 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.

Step 3
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())
Expected output
    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 each account_id appears at most once in accounts. If not, pandas raises MergeError instead of quietly repeating tickets once per duplicate account row.
  • indicator=True adds a _merge column that records, for each row, whether it found a match: both, left_only or right_only.
Step 4
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)
Expected output
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).

Step 5
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)
Expected output
         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:00

For 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.

Step 6
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))
Expected output
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

Practice check · 3 questions

Filtering, joining and parsing

These questions use the ticket and account tables from this lab.

Q1. This line raises an error: `df[df['language'] == 'en' & df['chars'] > 20]`. What is the fix?
Q2. After `tickets.merge(accounts, on='account_id', how='left', indicator=True)`, two rows have `_merge == 'left_only'`. What does that tell you?
Q3. What does `pd.to_datetime(raw['created_at'], errors='coerce', utc=True)` do with the value `'not recorded'`?
Practice only: not graded, not saved, not evidence.

10. Apply it (stretch)

Push the lab further:

  1. 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.
  2. Count tickets per region and language with groupby(["region", "language"]).size(), then use .unstack(fill_value=0) to see which languages each region needs.
  3. 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.
  4. 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 one unknown plan.

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.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check