Ir para o conteúdo

Lição 9 · Duplicates and Identifiers

Removing Exact Duplicates

Find duplicate rows safely: define what makes a record unique, normalize values first, choose which copy to keep and never drop genuine repeat events.

A duplicate is a record that should appear once but appears more than once. It can double revenue, send two emails or inflate a user count. Removing duplicates sounds easy. The hard part is deciding what makes two records the same thing.

Define the grain

The grain of a table says what one row stands for. A table of order lines may repeat an order ID legitimately, once per product. There, the unique combination might be the order ID plus the line number.

Three situations look similar but differ:

Situation Example Action
Identical copy A file loaded twice Keep one
Same key, different values Two versions of one customer Resolve the conflict
Real repeat event Two coffees bought at the same price Keep both

If rows have no unique event ID and two real purchases can look identical, you cannot know from the data alone whether one is a copy. Check the source's totals or ask the owner.

Count before removing

Python Find repeated keys and conflicts

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first repeat can be collapsed, once you know the key is right. The second is a conflict: is the quantity 2 or 3? Dropping whichever comes second would be a guess dressed up as cleaning.

Normalize before comparing

"[email protected] " and "[email protected]" are different strings. If your business treats them as the same address, build a normalized comparison key and keep the original values.

Python Deduplicate on a normalized key

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Keep a record of which row replaced which. If other tables refer to ID 2, you must point them to ID 1 as well. casefold() is a stronger form of lowercasing designed for comparisons. Whether letter case matters is a rule of your data, not a universal fact. For some codes, ab12 and AB12 are different.

Choose which copy survives

When versions differ, write a survivorship rule:

  • Keep the most recently updated record.
  • Prefer a trusted source over others.
  • Prefer the record with more filled fields.
  • Combine fields: newest phone, earliest sign-up date.
Python pandas: keep the latest version

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

keep=False marks every member of a repeated group, which is what you want when reviewing them. drop_duplicates keeps rows according to their current order, so sort first. If two versions share the same timestamp but differ, add a tie-breaker, such as source priority. Also check for missing dates, which affect the sort.

Prevent them

Duplicates often come from reruns, retries and repeated form submissions. Prevention beats removal:

  • Give each event a unique ID at the source.
  • Add a unique constraint in the database.
  • Make loads idempotent: running the same load twice gives the same result.
  • Record which files you have already processed.

Common mistake: calling "remove duplicates" on only the visible columns of an export. If the export left out the line number or timestamp, genuine separate events look identical and get erased.

Verify

After deduplication, check that the key is unique, compare totals with a trusted source and check some removed rows by eye. Save the removed rows to a separate file so the change can be reversed.

Choosing a key

To find a key, ask what would make two rows impossible as separate facts. Candidates include a transaction ID from the source, or a combination such as device, timestamp and reading number. Test each candidate by counting the groups with more than one row, then read several of those groups in full.

Adding more columns to a key makes it stricter, so fewer rows count as duplicates. That is not automatically safer. If you include a column that differs between copies, such as the time the row was loaded, true copies will stop matching. Leave out technical columns like load time or file name when you compare content, but keep them in the table, because they help you explain where copies came from.

Duplicates across files

Repeats often appear only after you combine files. Check each file alone first, then check the combined table and count how many keys appear in more than one file. Overlapping date ranges in monthly exports are a likely cause: the last day of one export may also be in the next. If so, a rule based on the key and the latest export can handle it, once the owner agrees.

A short example of the risk

Suppose an export of coffee shop sales has columns for date, product and price, but no receipt number or time. Two customers each buy the same drink on the same day. The two rows are identical, and both are real sales. A blanket "remove identical rows" step would cut revenue, and it would cut it most for the most popular products, because they are the likeliest to repeat.

The right fix is to ask for an export that includes a transaction ID. If none exists, compare the row count and total with the till's daily summary. When they match, keep every row. When the export has exactly twice as much for one day, you have good evidence of a double load for that day. Write down which evidence you used, so that a reviewer can judge it.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. In an order-lines table, what does a repeated order ID mean?

    The grain is the order line, so the unique key probably includes a line number.
  2. 2. Two rows share a key but have different quantities. What should you do?

    A conflict needs a justified decision, not an accidental one based on row order.
  3. 3. What is an idempotent load?

    Idempotent loads make retries safe, which prevents duplicates.

Summary

  • Decide the grain and the unique key first.
  • Separate identical copies, conflicts and real repeats.
  • Compare normalized keys but keep originals and a mapping.
  • Use a written survivorship rule and prevent new duplicates.

Next: Fuzzy Matching and Record Linkage

Seu progresso fica salvo neste navegador. Não precisa de conta.