liveBook · Manning

Loc accessor

As explained in Pandas Workout: 200 exercises to make you a stronger data analyst

The pandas .loc accessor selects rows and columns by labels or label-based slices, including Boolean masks.

The pandas `.loc` accessor selects by labels rather than numeric positions. On a Series, use a label to retrieve its value; on a DataFrame, use `.loc[row_selector, column_selector]` to narrow both dimensions. Think of the row selector as choosing records and the column selector as choosing the fields needed to answer a question. Unlike `.iloc`, which uses positions, `.loc` follows the index. On DataFrames, this distinction matters: square brackets select columns, while `.loc` selects rows and optionally columns. section 1.3 section 2.0

A label slice with `.loc` includes both endpoints. If monthly scores use month names as their index, `s.loc['Sep':'Jan']` includes January, then `.mean()` can calculate the first-half average. This is friendlier for named indexes, but differs from ordinary Python slices, whose stop is excluded. With repeated index labels, a lookup can return a Series rather than one scalar; for example, `s.loc['Mon']` returns every Monday value, allowing `s.loc['Mon'].mean()` to calculate the Monday average. section 1.3 section 1.19

Use the two selectors independently, then combine them as questions become more precise:

  • Retrieve one cell with `df.loc['a', 'x']`, selected rows with `df.loc[['a', 'c'], 'x']`, or selected columns with `df.loc['a', ['v', 'y']]`. Lists provide label-based fancy indexing. section 2.8
  • Filter rows with a Boolean Series. `df.loc[df['sales'] > df['sales'].mean(), ['product_id', 'name']]` keeps above-average products while returning only two columns. section 2.14
  • Combine conditions with `&` or use `isin`. For example, select rides matching several conditions, then count only the relevant column rather than every column. section 3.2
  • Query an index directly after `set_index`. Setting `Issue Date` as the index makes `.loc['01/02/2020 12:00:00 AM', 'Vehicle Make']` a direct date-based lookup. section 4.2

Fill missing sales without chained assignment

After concatenating new products, select the new row labels and the `sales` column in one operation: `df.loc[[5, 6, 7], 'sales'] = [100, 200, 75]`. The same shape works for retrieval before assignment, so `df.loc[[5, 6, 7], 'sales']` reveals the missing values. Keeping the Boolean row mask and column selector inside one `.loc[...]` expression is also the recommended pattern for updates such as `df.loc[df['temp'] < 0, 'temp'] = 0`; chained selections like `df[df['temp'] < 0]['temp'] = 0` can trigger `SettingWithCopyWarning`. section 2.10 section 2.26

`.loc` is useful beyond filtering. Assign `NaN` to selected temperature readings before interpolation, isolate selected fields before grouping or plotting, and select matching institutions before counting or joining. For repeated analytical queries, use the accessor as the point where a Boolean condition becomes a smaller, purposeful object. Alternative query forms, including `df.query` and `df.eval`, can express comparable filters and can be timed with `timeit` when performance matters. section 2.22 section 11.2 section 12.10

Figure 2.9 Graphical depiction of df.loc[df['sales'] > df['sales'].mean(), ['product_id', 'name']]

This diagram shows the common two-part pattern: a Boolean row selector followed by a list of columns, producing a focused result. section 2.14

How Pandas Workout: 200 exercises to make you a stronger data analyst covers it

How deep it goes
Works through label lookups, inclusive slices, repeated labels, Boolean masks, two-axis selection, and assignment, without detailing pandas internals.
Examples
Uses monthly scores, product sales, taxi rides, parking tickets, temperature outages, institutions, and city-growth plots.
What it assumes
Assumes familiarity with Series, DataFrames, indexes, columns, and Boolean comparisons while reinforcing their selection roles.
What you can do after
Apply it via pandas to retrieve and update labeled subsets with row masks and column selectors while avoiding chained-assignment warnings.
How it connects
Connects label-based indexing with iloc, Boolean indexing, set_index, query, eval, interpolation, groupby, and visualization.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pandas Workout: 200 exercises to make you a stronger data analyst. The section links point to the parts of the book it draws on.