DataFrames & filtering
Filtering is not a loop. It is a column of True and False laid over your rows.
Before you start
A **DataFrame** is a table — rows and columns — like a spreadsheet or a database table. Pandas is the Python library that gives you DataFrames and hundreds of operations on them.
To "filter" a DataFrame means: keep only some of the rows. In pandas you almost never write a for-loop for this. Instead, you build a column of True/False (a **boolean mask**) and lay it over the frame — rows aligned with True are kept.
This lesson shows the mask forming, then being applied, and explains why this vectorised approach is orders of magnitude faster than iterating row by row.
df
a DataFrame is columns, each with one type| Row | regionobject | repobject | amountint64 |
|---|---|---|---|
| 0 | north | Ana | 120 |
| 1 | south | Ben | 80 |
| 2 | north | Cal | 200 |
| 3 | east | Dee | 95 |
| 4 | north | Eli | 150 |
5 rows × 3 columns
df.shape is (5, 3) — rows first, then columns.
Step 1 of 7. A DataFrame is a set of columns. Rows are how you read it, but columns are how it is stored. Each column is a single array with one dtype — `amount` is `int64`, `region` holds Python objects. That layout is why column operations are fast and why mixing types inside a column quietly makes everything slower.
Step 01 / 07
A DataFrame is a set of columns
Rows are how you read it, but columns are how it is stored. Each column is a single array with one dtype — amount is int64, region holds Python objects.
That layout is why column operations are fast and why mixing types inside a column quietly makes everything slower.
import pandas as pddf = pd.read_csv("sales.csv")df.shape # (5, 3) — rows, columnsdf.dtypes # per-column typesdf["amount"] # one column: a Seriesmask = df["amount"] > 100 # a boolean Seriesdf[mask] # keep rows where mask is Truedf[(df["amount"] > 100) & (df["region"] == "north")]df.loc[df["amount"] > 100, "amount"] = 0 # filter and assign