Python / Data Science Essentials Interview Questions
What is the difference between df.loc[] and df.iloc[] in Pandas?
This distinction is tested in almost every Pandas interview. The short version: loc selects by label; iloc selects by integer position. They look similar but behave very differently, especially when the DataFrame index is not a default RangeIndex.
import pandas as pd
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Carol', 'Dave'],
'score': [88, 72, 95, 61],
'city': ['NYC', 'LA', 'NYC', 'Chicago'],
}, index=[10, 20, 30, 40]) # non-default index!
# --- loc: label-based ---
df.loc[20] # row with index label 20 (Bob)
df.loc[10:30] # rows 10, 20, 30 — INCLUSIVE stop
df.loc[10, 'name'] # single value: 'Alice'
df.loc[[10, 40], ['name', 'score']] # multiple rows and columns
df.loc[df['score'] >= 80] # boolean mask selection
# --- iloc: position-based ---
df.iloc[0] # first row (Alice) — positional 0
df.iloc[0:2] # rows 0 and 1 — EXCLUSIVE stop (like Python slicing)
df.iloc[0, 1] # row 0, column 1: 88
df.iloc[-1] # last row (Dave)
df.iloc[:, 0] # entire first column
# --- [] shorthand ---
df['name'] # single column as Series
df[['name', 'city']] # multiple columns as DataFrame
df[df['score'] > 80] # boolean filtering — OK for rows onlyThe classic trap: loc stop is inclusive; iloc stop is exclusive. This asymmetry trips up even experienced developers. When in doubt, prefer explicit loc or iloc over the [] shorthand to avoid ambiguity.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
