Data analysis with pandas · Lesson 4 of 15
Selecting columns and rows: loc and iloc
Pick the columns and rows you need: by column name, by row label with loc and by position with iloc, including single cells and slices.
Most of the time you need only part of a table: a few columns, some rows, or a single value. pandas gives you three tools: square brackets for columns, loc for labels and iloc for positions.
Columns
One column name in brackets gives a Series. A list of names (so double brackets) gives a smaller DataFrame with those columns in the order you list them.
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "notebook", "folder", "stapler", "ruler"],
"price": [1.50, 3.20, 2.00, 6.90, 1.10],
"stock": [120, 40, 0, 15, 60],
})
print(df["item"])
print(df[["item", "stock"]])0 pen
1 notebook
2 folder
3 stapler
4 ruler
Name: item, dtype: object
item stock
0 pen 120
1 notebook 40
2 folder 0
3 stapler 15
4 ruler 60Rows and cells by label: loc
df.loc[row, column] selects by label. With the default index the labels are 0, 1, 2 …, but it is still the label that counts, not the position. A slice with loc includes the end label, unlike normal Python slices.
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "notebook", "folder", "stapler", "ruler"],
"price": [1.50, 3.20, 2.00, 6.90, 1.10],
"stock": [120, 40, 0, 15, 60],
})
print(df.loc[1])
print(df.loc[1, "price"])
print(df.loc[1:3, ["item", "price"]])item notebook
price 3.2
stock 40
Name: 1, dtype: object
3.2
item price
1 notebook 3.2
2 folder 2.0
3 stapler 6.9loc[1:3] gives rows 1, 2 and 3: the end is included.
Labels become more useful when they mean something. set_index turns a column into the row labels, so you can look up a row by name.
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "notebook", "folder", "stapler", "ruler"],
"price": [1.50, 3.20, 2.00, 6.90, 1.10],
"stock": [120, 40, 0, 15, 60],
})
by_item = df.set_index("item")
print(by_item)
print(by_item.loc["stapler", "price"])
print(by_item.loc[["pen", "ruler"], "stock"])price stock item pen 1.5 120 notebook 3.2 40 folder 2.0 0 stapler 6.9 15 ruler 1.1 60 6.9 item pen 120 ruler 60 Name: stock, dtype: int64
Rows and cells by position: iloc
df.iloc[row, column] counts positions from 0, like a list, whatever the labels are. Its slices exclude the end, as in normal Python slicing [start:stop:step]. Negative numbers count from the end. Rule of thumb: use loc when you know names, iloc when you know positions (the first 3 rows, the last column).
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "notebook", "folder", "stapler", "ruler"],
"price": [1.50, 3.20, 2.00, 6.90, 1.10],
"stock": [120, 40, 0, 15, 60],
})
print(df.iloc[0])
print(df.iloc[-1, 0])
print(df.iloc[1:3, 0:2])item pen
price 1.5
stock 120
Name: 0, dtype: object
ruler
item price
1 notebook 3.2
2 folder 2.0Changing a value
loc also works on the left side of =, to change one cell. Always do it in one step, df.loc[row, column] = value. Writing df["stock"][2] = 50 is called chained assignment: it may change a copy instead of your table, and pandas warns about it.
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "notebook", "folder", "stapler", "ruler"],
"price": [1.50, 3.20, 2.00, 6.90, 1.10],
"stock": [120, 40, 0, 15, 60],
})
df.loc[2, "stock"] = 50
print(df.loc[2])item folder price 2.0 stock 50 Name: 2, dtype: object
✎ Exercise
From the shop table, print the item and price columns of the first 3 rows using iloc. Then print the price of the notebook using set_index and loc.
Hint: iloc[0:3, 0:2] takes rows 0-2 and columns 0-1. Then set_index("item").loc["notebook", "price"].
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "notebook", "folder", "stapler", "ruler"],
"price": [1.50, 3.20, 2.00, 6.90, 1.10],
"stock": [120, 40, 0, 15, 60],
})
# your code here
Expected output:
item price 0 pen 1.5 1 notebook 3.2 2 folder 2.0 3.2
Show a solution
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "notebook", "folder", "stapler", "ruler"],
"price": [1.50, 3.20, 2.00, 6.90, 1.10],
"stock": [120, 40, 0, 15, 60],
})
print(df.iloc[0:3, 0:2])
print(df.set_index("item").loc["notebook", "price"])item price 0 pen 1.5 1 notebook 3.2 2 folder 2.0 3.2
Check yourself
1. What does df[["a", "b"]] return?
A list of column names inside the brackets gives a DataFrame with just those columns.
2. With the default index, how many rows does df.loc[0:2] return?
loc slices include the end label, so rows 0, 1 and 2.
3. How many rows does df.iloc[0:2] return?
iloc works like a Python slice: the end position is left out, so rows 0 and 1.
4. What is the safe way to set one value?
One loc call with row and column changes the table itself. The chained form may change a temporary copy.