PY-401 · pandas basics
Selecting rows and columns
⏱ 8 min 🐍 Real Python 3 🎬 Animated ✓ Completed
⚡ The 30-second answer
Use df["col"] for one column and df[["a", "b"]] for several. For rows, df.loc[...] selects by label and df.iloc[...] selects by position, and both take a row and a column: df.loc["B1", "price"]. The rule to remember: loc means labels, iloc means integer positions.
- Select one or several columns
- Select rows by label with loc
- Select rows by position with iloc
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
import pandas as pddf = pd.DataFrame({"product": ["Tea", "Coffee", "Cake", "Juice"],"units": [12, 7, 4, 9],"price": [2.5, 3.0, 4.5, 2.0],}, index=["A1", "A2", "B1", "B2"])print(df["product"].tolist())print(df[["product", "price"]])print(df.loc["B1"])print(df.iloc[0, 1])print(df.loc["A2":"B1", "units"].tolist())
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
['Tea', 'Coffee', 'Cake', 'Juice']
product price
A1 Tea 2.5
A2 Coffee 3.0
B1 Cake 4.5
B2 Juice 2.0
product Cake
units 4
price 4.5
Name: B1, dtype: object
12
[7, 4] 🎯 From df, set price_b2 to the price of row "B2" using loc, and first_two to the first two rows using iloc.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
price_b2 = df.loc["B2", "price"] and first_two = df.iloc[:2]
- The problemA stock list has a product code on every row. The warehouse asks for the price of item B1 and the units of the first item on the list. One is a label, one is a position, and pandas has a tool for each.
- The Python idea
df["col"] # one columnUsedf["col"]for one column anddf[["a", "b"]]for several. - In real lifeA hotel booking table is indexed by room number. Reception reads one room with
bookings.loc[214], while a report takes the 10 most recent rows withbookings.iloc[-10:].
Start with a question
A stock list has a product code on every row. The warehouse asks for the price of item B1 and the units of the first item on the list. One is a label, one is a position, and pandas has a tool for each.
Every question you ask a table starts with picking the right rows and columns. Getting loc and iloc right avoids silent wrong answers.
Explain it like I'm 10
loc is finding a house by its name on the gate. iloc is finding it by counting: the third house on the street. Both get you to a house, in different ways.
The technical explanation
df["product"] gives one column as a Series. Double brackets, df[["product", "price"]], give a smaller DataFrame.
df.loc["B1"] is the row labelled B1. df.loc["B1", "price"] is one cell.
df.iloc[0] is the first row whatever its label. df.iloc[0, 1] is row 0, column 1.
Both accept slices and lists: df.loc["A2":"B1", "units"] or df.iloc[:2, [0, 2]].
| loc | iloc | |
|---|---|---|
Selects by | Label (name) | Position (0, 1, 2 …) |
Slice end | Included | Excluded |
Example | df.loc["B1", "price"] | df.iloc[2, 2] |
Syntax
df["col"] # one column
df[["a", "b"]] # several columns
df.loc[row_label, col_label]
df.iloc[row_pos, col_pos] Real-world scenario
A hotel booking table is indexed by room number. Reception reads one room with bookings.loc[214], while a report takes the 10 most recent rows with bookings.iloc[-10:].
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
🏆 Every lesson counts toward your certificate Next: Filtering rows →Questions people ask
What is the difference between loc and iloc in pandas?
loc selects rows and columns by their labels and includes the end of a slice. iloc selects by integer position and excludes the end of a slice, like normal Python indexing.
Why do I get a SettingWithCopyWarning in pandas?
You probably changed a value on a selection made in two steps, such as df[df.x > 1]["y"] = 0, which may change a temporary copy. Do it in one step with df.loc[df.x > 1, "y"] = 0.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner What is the difference between loc and iloc in pandas?
loc selects rows and columns by their labels and includes the end of a slice. iloc selects by integer position and excludes the end of a slice, like normal Python indexing.
beginner Why do I get a SettingWithCopyWarning in pandas?
You probably changed a value on a selection made in two steps, such as df[df.x > 1]["y"] = 0, which may change a temporary copy. Do it in one step with df.loc[df.x > 1, "y"] = 0.
intermediate Which selects by label?
loc. loc uses labels; iloc uses integer positions.
intermediate df[["a", "b"]] returns…
A DataFrame with columns a and b. A list of names in the brackets gives a smaller DataFrame.
Quick revision
Remember
- Select one or several columns
- Select rows by label with loc
- Select rows by position with iloc
- A loc slice includes the end label (
"A2":"B1"keeps B1), but an iloc slice stops before the end position, like normal Python.
Syntax
df["col"] # one column
df[["a", "b"]] # several columns
df.loc[row_label, col_label]
df.iloc[row_pos, col_pos] Official documentation
- Indexing and selecting data (docs.python.org)