Skip to content
tezvyn:

Pandas loc versus iloc indexing

Source: interviewEasyHow cards are made

Summary

practical pandas selection fluency.

Key points

loc selects by label and is inclusive of both endpoints; iloc selects by integer position and is exclusive of the stop; passing a string label to iloc fails.

What's really being asked

This checks day-to-day pandas competence and attention to the inclusive-versus-exclusive slicing rule that trips up many engineers. It signals whether you write correct data-wrangling code.

The full answer

The loc accessor selects by label: you pass index values and column names. Its slice is inclusive of both the start and the stop label, so df.loc['a':'c'] returns rows a, b, and c. The iloc accessor selects by integer position from 0 to length minus 1, following standard Python slicing where the stop is excluded, so df.iloc[0:3] returns positions 0, 1, and 2. When the DataFrame has a default integer RangeIndex the two can look similar, but the inclusive-versus-exclusive boundary still differs.

The mistakes people make

Saying both are interchangeable. Claiming both slices are exclusive, or both inclusive. Believing loc always needs strings; loc works on any label type including integers when the index is integer-labeled. Forgetting that mixing them silently produces wrong rows rather than always erroring.

What usually comes next

What does df.loc index when the index itself is integers but unsorted. How do boolean masks interact with loc. What is the difference between df['col'] and df.loc[:, 'col'].

A concrete example

Suppose df has a string index ['x', 'y', 'z']. Calling df.loc['x'] returns the first row by label and works fine. Calling df.iloc['x'] raises a TypeError because iloc demands integer positions, not labels. Conversely df.iloc[0] returns the first row, while df.loc[0] raises a KeyError because no row is labeled 0. This contrast is exactly the example interviewers want, showing each accessor fails when given the other's input type.

Interview question

For a DataFrame with a string index, which call raises an error and why?

  • a.df.loc[:, :], because full slices are disallowed
  • b.df.iloc[0], because position 0 is reserved
  • c.df.loc['x'], because loc cannot take a single label
  • d.df.iloc['x'], because iloc requires integer positions not labelsCorrect
Why?

iloc is strictly positional and rejects a string label, raising a TypeError. df.loc['x'] and df.iloc[0] both work correctly on a string-indexed frame.

Just read this? Test yourself on what you have been reading.

Read the original → pandas.pydata.org

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Every open role lists the topics its interview covers, so you can prepare for the real thing rather than guessing.

See open roles