Selecting with loc and iloc
"What was the branch on sale 4?" "Show rows 2 to 4, just branch and copies." A DataFrame has two ways to point at cells: by the labels printed on it, or by counting positions. pandas gives each its own tool, and mixing them up is the most common beginner bug in pandas.
The rule
locuses labels and includes the end;ilocuses positions and excludes it.
We keep using sales, now with its revenue column (8 rows; columns date, branch, genre, copies, price, revenue).
sales.loc[4, "branch"] # 'Delhi' row label 4, column named branch
sales.loc[2:4, ["branch", "copies"]] # rows labelled 2, 3 AND 4
sales.iloc[4, 1] # 'Delhi' 5th row, 2nd column
sales.iloc[2:4, [1, 3]] # rows at positions 2 and 3 onlyBoth take [rows, columns], and both accept a single item, a list, or a slice in each part. A colon alone means "all": sales.loc[:, "price"] is the whole price column.
So far labels and positions look identical, because the default index is 0, 1, 2… The difference becomes obvious once the index is something else:
by_date = sales.set_index("date")
by_date.loc["2024-03-02"] # both rows with that date label
by_date.iloc[0] # the first row, whatever its labelloc also takes a boolean mask for the rows, which is how the next lesson filters data:
sales.loc[sales["copies"] > 4, "branch"] # Delhi, Chennai