Selecting with loc and iloc
Picking exactly the rows and columns you need is the most frequent thing you do in pandas. Square brackets alone (df["col"]) are fine for columns, but for rows, or rows and columns together, use the two dedicated indexers:
| Indexer | Selects by | Slice end |
|---|---|---|
df.loc[rows, cols] |
labels (index values, column names) | included |
df.iloc[rows, cols] |
integer positions (0, 1, 2…) | excluded, like Python |
All examples use this small table of mountain huts, indexed by hut name:
import pandas as pd
huts = pd.DataFrame({
"region": ["Alps", "Alps", "Tatra", "Pyrenees", "Tatra"],
"altitude": [2850, 3260, 1960, 2450, 1680],
"beds": [40, 120, 28, 64, 35],
"price": [68, 92, 31, 55, 29],
}, index=["Edelweiss", "Gletscher", "Murowaniec", "Refugi Blanc", "Chata Poľana"])
print(huts) region altitude beds price
Edelweiss Alps 2850 40 68
Gletscher Alps 3260 120 92
Murowaniec Tatra 1960 28 31
Refugi Blanc Pyrenees 2450 64 55
Chata Poľana Tatra 1680 35 29
loc: by label
import pandas as pd
huts = pd.DataFrame({
"region": ["Alps", "Alps", "Tatra", "Pyrenees", "Tatra"],
"altitude": [2850, 3260, 1960, 2450, 1680],
"beds": [40, 120, 28, 64, 35],
"price": [68, 92, 31, 55, 29],
}, index=["Edelweiss", "Gletscher", "Murowaniec", "Refugi Blanc", "Chata Poľana"])
print(huts.loc["Murowaniec"]) # one row -> Series
print(huts.loc["Gletscher", "beds"]) # one cell -> scalar
print(huts.loc[["Edelweiss", "Refugi Blanc"], ["region", "price"]])
print(huts.loc["Gletscher":"Refugi Blanc", "altitude":"beds"])region Tatra
altitude 1960
beds 28
price 31
Name: Murowaniec, dtype: object
120
region price
Edelweiss Alps 68
Refugi Blanc Pyrenees 55
altitude beds
Gletscher 3260 120
Murowaniec 1960 28
Refugi Blanc 2450 64
Note the last line: a label slice like "Gletscher":"Refugi Blanc" includes both ends, and so does the column slice "altitude":"beds".
iloc: by position
import pandas as pd
huts = pd.DataFrame({
"region": ["Alps", "Alps", "Tatra", "Pyrenees", "Tatra"],
"altitude": [2850, 3260, 1960, 2450, 1680],
"beds": [40, 120, 28, 64, 35],
"price": [68, 92, 31, 55, 29],
}, index=["Edelweiss", "Gletscher", "Murowaniec", "Refugi Blanc", "Chata Poľana"])
print(huts.iloc[0]) # first row
print(huts.iloc[-1, 1]) # last row, second column
print(huts.iloc[1:3]) # rows 1 and 2 (3 is excluded)
print(huts.iloc[[0, 2], [0, 3]])
print(huts.iloc[:, -1].to_list()) # every row, last columnregion Alps
altitude 2850
beds 40
price 68
Name: Edelweiss, dtype: object
1680
region altitude beds price
Gletscher Alps 3260 120 92
Murowaniec Tatra 1960 28 31
region price
Edelweiss Alps 68
Murowaniec Tatra 31
[68, 92, 31, 55, 29]
iloc behaves exactly like slicing a Python list: 1:3 means positions 1 and 2.
Selecting with conditions
loc also accepts a boolean mask for the rows, which combines filtering and column selection in one step:
import pandas as pd
huts = pd.DataFrame({
"region": ["Alps", "Alps", "Tatra", "Pyrenees", "Tatra"],
"altitude": [2850, 3260, 1960, 2450, 1680],
"beds": [40, 120, 28, 64, 35],
"price": [68, 92, 31, 55, 29],
}, index=["Edelweiss", "Gletscher", "Murowaniec", "Refugi Blanc", "Chata Poľana"])
print(huts.loc[huts["altitude"] > 2000, ["region", "altitude"]])
print(huts.loc[huts["region"] == "Tatra", "price"].mean()) region altitude
Edelweiss Alps 2850
Gletscher Alps 3260
Refugi Blanc Pyrenees 2450
30.0
Changing values with loc
Because loc names rows and columns at the same time, it's also the safe way to assign values:
import pandas as pd
huts = pd.DataFrame({
"region": ["Alps", "Alps", "Tatra", "Pyrenees", "Tatra"],
"price": [68, 92, 31, 55, 29],
}, index=["Edelweiss", "Gletscher", "Murowaniec", "Refugi Blanc", "Chata Poľana"])
huts.loc["Edelweiss", "price"] = 72 # one cell
huts.loc[huts["region"] == "Tatra", "price"] += 5 # every Tatra hut
huts.loc["Bivacco Rosso"] = ["Alps", 0] # new row
print(huts) region price
Edelweiss Alps 72
Gletscher Alps 92
Murowaniec Tatra 36
Refugi Blanc Pyrenees 55
Chata Poľana Tatra 34
Bivacco Rosso Alps 0
Note: Avoid "chained" assignment like
huts[huts["region"] == "Tatra"]["price"] = 40. The first bracket creates a temporary copy, so the assignment may change the copy instead ofhuts. pandas warns about this;loc[mask, "price"] = 40always works.
at and iat for single values
To read or write exactly one cell, at (by label) and iat (by position) are faster shortcuts:
import pandas as pd
huts = pd.DataFrame({
"altitude": [2850, 3260, 1960],
"beds": [40, 120, 28],
}, index=["Edelweiss", "Gletscher", "Murowaniec"])
print(huts.at["Gletscher", "altitude"])
print(huts.iat[2, 1])
huts.at["Murowaniec", "beds"] = 30
print(huts)3260
28
altitude beds
Edelweiss 2850 40
Gletscher 3260 120
Murowaniec 1960 30
Test yourself
With the default index, what does df.iloc[2:4] return?
- Rows at positions 2, 3 and 4
- Rows at positions 2 and 3
- Rows at positions 3 and 4
- Columns 2 and 3
Given an index of letters a–e, what does df.loc["b":"d"] return?
- Rows b and c
- Rows b, c and d
- Rows c and d
- An error
Which line safely sets the price to 0 for every row where stock is 0?
- df[df["stock"] == 0]["price"] = 0
- df.loc[df["stock"] == 0, "price"] = 0
- df.iloc[df["stock"] == 0, "price"] = 0
- df.at[df["stock"] == 0] = 0