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.

About 15 minutes · code runs in your browser, nothing to install

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.

Pythoneditable
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"]])
Output
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     60

Rows 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.

Pythoneditable
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"]])
Output
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.9

loc[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.

Pythoneditable
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"])
Output
          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).

Pythoneditable
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])
Output
item     pen
price    1.5
stock    120
Name: 0, dtype: object
ruler
       item  price
1  notebook    3.2
2    folder    2.0

Changing 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.

Pythoneditable
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])
Output
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"].

Your codewrite your answer, then Run
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
Solutioneditable
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"])
Output
       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?

2. With the default index, how many rows does df.loc[0:2] return?

3. How many rows does df.iloc[0:2] return?

4. What is the safe way to set one value?

Spotted a mistake on this page? Tell us