Pandas loc versus iloc indexing
practical pandas selection fluency.
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 THIS TESTS 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.
A GOOD ANSWER COVERS 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.
COMMON WRONG ANSWERS 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.
LIKELY FOLLOW-UPS 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'].
ONE 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.
Read the original → pandas.pydata.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.