A column selector specifies which DataFrame columns an indexer should return. With .loc, place it after the row condition, so filtering and column selection happen together. section 2.14
Keep only useful columns
Suppose a sales DataFrame should show products whose sales exceed the average, but only display product_id and name. The boolean row condition goes first; ['product_id', 'name'] is the column selector. The same narrowing can follow a df.query(...) result with square brackets. section 2.14
Column selectors also support progressively richer analytical tasks:
- Select INSTNM after filtering bachelor-level Computer Science programs, then call unique().size to count distinct institutions. section 13.3
- Select CONTROL and INSTNM before grouping by CONTROL to compare institution categories offering those programs. section 13.3
- Select identifiers and measures, such as OPEID6 and TUITIONFEE_OUT, before setting an index and joining datasets. section 13.3
df.loc[
df['sales'] > df['sales'].mean(), #1
['product_id', 'name'] #2
]
Inspect the compact .loc pattern: a boolean row selector followed by a list of requested columns. section 2.14
