liveBook · Manning

Fancy indexing

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

Fancy indexing selects multiple positions or labels by supplying an index collection rather than a single index.

Fancy indexing selects several positions or labels at once by placing an index collection inside square brackets. With a Series, s.loc[[2, 4]] returns both indexed elements while preserving their original labels. With a DataFrame, df.loc uses the first argument for rows and the second for columns, so lists can select either dimension. section 1.13 section 2.8

Use fancy indexing with pandas objects to:

  • Retrieve rows a and c from column x with df.loc[['a', 'c'], 'x']. section 2.8
  • Retrieve row a from columns v and y, or combine lists to select multiple rows and columns. section 2.8
  • Combine label lists with boolean indexes, such as selecting rows where x exceeds 200 and columns where c exceeds 135. section 2.8
  • Distinguish a list of labels from a mask index: labels name positions, while True and False values select matching positions. section 1.13

Fill missing sales for several products

After adding products at indexes 5, 6, and 7, select their sales column with df.loc[[5, 6, 7], 'sales']. Assigning [100, 200, 75] updates all three missing values in one operation. A scalar on the right would instead be broadcast to every matching cell. section 2.10 section 2.8

df.loc[['a', 'c'],   #1
       ['v','y']]    #2

Inspect the two-list loc expression that selects rows a and c together with columns v and y. section 2.8

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

How deep it goes
Explains list-based and boolean selection through loc syntax, returned shapes, mask distinctions, and multi-value assignment.
Examples
Uses labeled Series values, a five-by-five DataFrame, conditional selectors, and missing product sales filled by indexed assignment.
What it assumes
Assumes familiarity with pandas indexes, Series, DataFrames, square-bracket indexing, and boolean comparisons.
What you can do after
Apply it via pandas loc to retrieve or update selected positions, rows, columns, and conditionally matched cells.
How it connects
Connects pandas Series, DataFrame selection, boolean indexing, broadcasting, and assignment.

Also explained in

Compare how 2 books explain fancy indexing →

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.