Data Analysis with Python and pandas
Selecting and Filtering Data
In this lesson you will
- Select one or more columns
- Filter rows with a condition
- Combine conditions and sort the result
Introduction
Most analysis starts with narrowing down: just these columns, just the rows that match a rule. This lesson uses the same df from the last lesson (products, category, price and units).
Choose columns
Python
print(df[["product", "price"]].head(2)) product price
0 Notebook 3.5
1 Pen Set 5.0A single name in brackets gives a Series. A list of names, with double brackets, gives a smaller DataFrame.
Filter rows
Put a condition inside the brackets. pandas keeps only the rows where it is true.
Python
print(df[df["price"] > 10]) product category price units
2 Backpack Bags 29.9 2
3 Bottle Kitchen 12.0 6
5 Backpack Bags 29.9 3Read it as "the rows of df where price is more than 10".
Quick quiz
What does df[df['units'] >= 8] return?
Combine conditions
Use & for and, | for or, and put each condition in its own parentheses:
Python
print(df[(df["category"] == "Stationery") & (df["units"] >= 8)]) product category price units
0 Notebook Stationery 3.5 10
4 Notebook Stationery 3.5 8Do not use the words and or or here. They do not work on whole columns.
Sort
Python
print(df.sort_values("units", ascending=False).head(3)) product category price units
0 Notebook Stationery 3.5 10
4 Notebook Stationery 3.5 8
3 Bottle Kitchen 12.0 6ascending=False puts the biggest first.
Try it yourself
Show only the product and units of items that cost less than 10, sorted by units from highest to lowest.
Summary
df[["a", "b"]]selects columns, anddf[condition]selects rows.- Combine conditions with
&and|, each inside parentheses. sort_valuesorders rows by a column.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading