liveBook · Manning

Iloc

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

The pandas iloc accessor selects Series or DataFrame elements by integer position or position-based slices.

`iloc` selects pandas data by integer position. Use it when the order of values or rows matters more than their labels: position 0 is first, and negative positions count backward from the end. Positional slices follow normal Python behavior, so the stop position is excluded. section 1.3 section 6.2

For a Series with month labels, `s.iloc[:5]` still means the first five values, regardless of those labels. This differs from `loc`: `s.loc['Sep':'Jan']` selects by label and includes January. Choosing between them makes the selection rule visible in the code. section 1.3

Use positional selection to answer order-based questions:

  • Take an initial segment with `s.iloc[:5]`, then calculate a result such as its mean. section 1.3
  • Take a final segment with `s.iloc[-20:]`; the negative start counts from the end. section 6.2
  • Retrieve a DataFrame row by its row position with `df.iloc[0]`; square brackets normally select columns instead. section 2.0

Average the 20 longest taxi rides

After sorting taxi rides by `trip_distance` in descending order, select `total_amount` and then use `.iloc[:20]`. The positions now represent rank in the sorted result, whereas the original index labels remain unordered. Chain `.mean().round(2)` to obtain the rounded average. With ascending sorting, use `.iloc[-20:]` for the same longest-trip group. section 6.2

Figure 6.3 Running sort_values on a data frame, then keeping only one column, and then getting only the first rows with iloc

Inspect the compact chain that sorts rides, selects one column, and keeps its first 20 positional values. section 6.2

A useful check is to ask whether “first” means a label or a current position. After sorting, use `iloc` for a fixed number of rows; using `loc[:20]` would follow index labels and can return more rows than intended. section 6.2

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

How deep it goes
Explains positional slices, negative indexing, and the practical distinction from label-based loc without detailing pandas internals.
Examples
Uses monthly student scores and sorted NYC taxi rides to select first or last positional groups.
What it assumes
Assumes familiarity with Series, DataFrames, indexes, slices, and basic aggregation methods.
What you can do after
Apply it via pandas to select position-based rows or values reliably when labels differ from analytical order.
How it connects
Connects positional indexing with Series, DataFrame, loc, sorting, mean, and method chaining.

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.