Python for Excel users · Lesson 4 of 14
Filter and sort data like Excel AutoFilter
Replace AutoFilter and Sort with pandas: keep rows that match one or more conditions, filter text, pick a top 3 and sort by several columns.
In Excel you click the filter arrow, tick some boxes and the other rows disappear. In pandas you write the condition, and you get a new table with only the matching rows. The original stays untouched, so there is no "clear filter" to forget.
One condition
df["Units"] > 100 checks every row and gives a column of True/False, called a mask. Put the mask inside df[...] and only the True rows stay.
import pandas as pd
df = pd.DataFrame({
"Region": ["North", "South", "North", "East", "South", "East"],
"Product": ["Lamp", "Chair", "Desk", "Lamp", "Desk", "Chair"],
"Units": [120, 85, 240, 60, 155, 90],
})
print(df["Units"] > 100)
print(df[df["Units"] > 100])0 True 1 False 2 True 3 False 4 True 5 False Name: Units, dtype: bool Region Product Units 0 North Lamp 120 2 North Desk 240 4 South Desk 155
The row labels (0, 2, 4) are kept, so you can see where each row came from.
Text filters work the same way: == equals, != does not equal. isin is the AutoFilter tick list: it keeps rows whose value is one of several.
import pandas as pd
df = pd.DataFrame({
"Region": ["North", "South", "North", "East", "South", "East"],
"Product": ["Lamp", "Chair", "Desk", "Lamp", "Desk", "Chair"],
"Units": [120, 85, 240, 60, 155, 90],
})
print(df[df["Region"] == "North"])
print(df[df["Product"].isin(["Lamp", "Desk"])])Region Product Units 0 North Lamp 120 2 North Desk 240 Region Product Units 0 North Lamp 120 2 North Desk 240 3 East Lamp 60 4 South Desk 155
Several conditions: AND and OR
Filtering two columns in Excel means AND. In pandas you join masks with & (and) or | (or), and each condition must be in its own brackets. ~ means NOT.
import pandas as pd
df = pd.DataFrame({
"Region": ["North", "South", "North", "East", "South", "East"],
"Product": ["Lamp", "Chair", "Desk", "Lamp", "Desk", "Chair"],
"Units": [120, 85, 240, 60, 155, 90],
})
print(df[(df["Region"] == "South") & (df["Units"] > 100)])
print(df[(df["Product"] == "Lamp") | (df["Units"] < 70)])
print(len(df[~(df["Region"] == "East")]))Region Product Units 4 South Desk 155 Region Product Units 0 North Lamp 120 3 East Lamp 60 4
Write and/or instead of &/| and pandas stops with a "truth value is ambiguous" error.
df[df["Product"].str.contains("ai")] and df[df["Product"].str.startswith("L")]. Lesson 10 covers text in detail.Sorting: A to Z, Z to A, several levels
sort_values is Excel's Sort dialog. Give a list of columns for several levels, and a matching list for ascending (False means largest first).
import pandas as pd
df = pd.DataFrame({
"Region": ["North", "South", "North", "East", "South", "East"],
"Product": ["Lamp", "Chair", "Desk", "Lamp", "Desk", "Chair"],
"Units": [120, 85, 240, 60, 155, 90],
})
print(df.sort_values("Units", ascending=False))
print(df.sort_values(["Region", "Units"], ascending=[True, False]))Region Product Units 2 North Desk 240 4 South Desk 155 0 North Lamp 120 5 East Chair 90 1 South Chair 85 3 East Lamp 60 Region Product Units 5 East Chair 90 3 East Lamp 60 2 North Desk 240 0 North Lamp 120 4 South Desk 155 1 South Chair 85
Second table: regions A to Z, and inside each region the largest number of units first.
Top 10 filter
Excel's "Top 10" number filter is nlargest; the bottom ones are nsmallest. reset_index(drop=True) renumbers the rows 0, 1, 2 if you want a clean result.
import pandas as pd
df = pd.DataFrame({
"Product": ["Lamp", "Chair", "Desk", "Shelf", "Rug", "Sofa"],
"Units": [120, 85, 240, 60, 155, 90],
})
top3 = df.nlargest(3, "Units").reset_index(drop=True)
print(top3)
print(df.nsmallest(1, "Units"))Product Units 0 Desk 240 1 Rug 155 2 Lamp 120 Product Units 3 Shelf 60
✎ Exercise
Keep the orders from Spain or Italy whose Amount is at least 50, sorted from the largest amount to the smallest, and print them.
Hint: Combine an isin() mask with (df["Amount"] >= 50) using &, then sort_values with ascending=False.
import pandas as pd
df = pd.DataFrame({
"Country": ["Spain", "Italy", "France", "Spain", "Italy", "Spain"],
"Amount": [75.0, 42.5, 99.0, 50.0, 130.0, 12.0],
})
# your code here
Expected output:
Country Amount 4 Italy 130.0 0 Spain 75.0 3 Spain 50.0
Show a solution
import pandas as pd
df = pd.DataFrame({
"Country": ["Spain", "Italy", "France", "Spain", "Italy", "Spain"],
"Amount": [75.0, 42.5, 99.0, 50.0, 130.0, 12.0],
})
mask = df["Country"].isin(["Spain", "Italy"]) & (df["Amount"] >= 50)
print(df[mask].sort_values("Amount", ascending=False))Country Amount 4 Italy 130.0 0 Spain 75.0 3 Spain 50.0
Check yourself
1. Which line keeps rows where Region is North AND Units is over 100?
Use & between masks, with each condition in brackets.
2. What is the pandas version of ticking three values in an AutoFilter list?
df[col].isin([a, b, c]) keeps rows whose value is in the list.
3. Does df[df["Units"] > 100] change df?
Filtering gives a new DataFrame. Store it in a variable if you want to keep it.