Python for Excel users · Lesson 12 of 14

Remove duplicates and check data in pandas

Remove duplicates like Excel, find invalid values the way Data Validation would, and flag rows instead of colouring them with conditional formatting.

About 15 minutes · code runs in your browser, nothing to install

Before any report, Excel users clean up: Data → Remove Duplicates, Data Validation's "Circle Invalid Data", and a few conditional formatting rules to make problems stand out. pandas does all three, and you can rerun the checks on every new file.

Remove Duplicates

duplicated() marks rows that appeared before (unlike Excel's duplicate-values highlight, the first copy is not marked); drop_duplicates() removes them. With subset you choose which columns must match, like ticking columns in Excel's dialog. keep="last" keeps the latest row instead of the first.

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "Email": ["[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"],
    "City": ["Porto", "Lyon", "Porto", "Turin", "Paris"],
})
print(df.duplicated().tolist())
print(df.drop_duplicates())
print(df.drop_duplicates(subset="Email", keep="last"))
Output
[False, False, True, False, False]
        Email   City
0  [email protected]  Porto
1  [email protected]   Lyon
3   [email protected]  Turin
4  [email protected]  Paris
        Email   City
2  [email protected]  Porto
3   [email protected]  Turin
4  [email protected]  Paris

Whole-row check: only row 2 is a copy. By email alone, Ben's older Lyon row goes too.

Data validation checks

Each validation rule is a mask that is True for bad rows. ~isin catches values outside a list, ~between numbers outside a range, isna blank cells. Count them, then look at the rows.

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "Order": [1, 2, 3, 4, 5, 6],
    "Status": ["Paid", "Open", "paid", "Open", "Sent", "Paid"],
    "Qty": [3, 0, 2, 150, 5, None],
})
checks = {
    "Status not in list": ~df["Status"].isin(["Paid", "Open", "Sent"]),
    "Qty not 1-100": ~df["Qty"].between(1, 100),
    "Qty blank": df["Qty"].isna(),
}
for rule, bad in checks.items():
    print(f"{rule}: {bad.sum()} row(s) {df.loc[bad, 'Order'].tolist()}")
Output
Status not in list: 1 row(s) [3]
Qty not 1-100: 3 row(s) [2, 4, 6]
Qty blank: 1 row(s) [6]

paid in lower case fails the list check, just as Excel's list validation would reject it. A blank Qty fails both Qty rules.

Tip: Fix what can be fixed safely before checking: df["Status"].str.strip().str.title() turns " paid" into Paid. Then the checks only show the real problems.

Conditional formatting becomes a flag column

In Excel you colour a cell red when a value is too high. In a script you add a flag column instead, so the rule is written down and you can filter, count or sort by it. np.select from IF, nested IF and IFS in pandas handles several levels.

Pythoneditable
import numpy as np
import pandas as pd

df = pd.DataFrame({
    "Rep": ["Ana", "Ben", "Chloe", "Dev", "Eva"],
    "Spend": [420, 1350, 980, 2100, 150],
})
df["Flag"] = np.select(
    [df["Spend"] > 2000, df["Spend"] > 1000],
    ["RED", "AMBER"], default="")
print(df)
print(df[df["Flag"] != ""].sort_values("Spend", ascending=False))
Output
     Rep  Spend   Flag
0    Ana    420
1    Ben   1350  AMBER
2  Chloe    980
3    Dev   2100    RED
4    Eva    150
   Rep  Spend   Flag
3  Dev   2100    RED
1  Ben   1350  AMBER

If the people who read the file want real colours, pandas can write them into the workbook. This needs openpyxl and jinja2 installed, so it runs on your computer.

On your computer: coloured cells
def colour(value):
    if value > 2000:
        return "background-color: #f4cccc"
    if value > 1000:
        return "background-color: #fff2cc"
    return ""

styled = df.style.map(colour, subset=["Spend"])
styled.to_excel("checked.xlsx", index=False)

style.map runs your rule on every cell of the chosen columns, like a conditional formatting rule.

✎ Exercise

Remove duplicate rows by Id (keep the first), then print the cleaned table and the list of Ids whose Age is not between 18 and 99.

Hint: drop_duplicates(subset="Id"), then ~df["Age"].between(18, 99) as the mask.

Your codewrite your answer, then Run
import pandas as pd

df = pd.DataFrame({
    "Id": [1, 2, 2, 3, 4, 5],
    "Age": [34, 17, 17, 45, 120, 28],
})
# your code here

Expected output:

   Id  Age
0   1   34
1   2   17
3   3   45
4   4  120
5   5   28
[2, 4]
Show a solution
Solutioneditable
import pandas as pd

df = pd.DataFrame({
    "Id": [1, 2, 2, 3, 4, 5],
    "Age": [34, 17, 17, 45, 120, 28],
})
df = df.drop_duplicates(subset="Id")
print(df)
bad = ~df["Age"].between(18, 99)
print(df.loc[bad, "Id"].tolist())
Output
   Id  Age
0   1   34
1   2   17
3   3   45
4   4  120
5   5   28
[2, 4]

Check yourself

1. Which option of drop_duplicates keeps the most recent copy?

2. Which mask finds Qty values outside 1 to 100?

3. Why use a flag column instead of only colouring cells?

Spotted a mistake on this page? Tell us