Data Analysis · pandas Core · lesson 6 of 12
Selecting with loc and iloc
about 15 minutes · free · runs in your browser
Two ways to point at a row
pandas gives you two accessors and it matters which you use:
.locselects by label — the index value and the column name..ilocselects by integer position, like a list.
df.loc[2] # the row labelled 2
df.loc[2, "city"] # one cell
df.loc[1:3] # rows 1 to 3 INCLUSIVE — labels, not positions
df.loc[:, ["city", "temp"]] # all rows, two columns
df.iloc[0] # the first row
df.iloc[0, 1] # first row, second column
df.iloc[0:2] # the first two rows — exclusive, like a list
The trap worth memorising: .loc slices are inclusive of the end, .iloc slices
are not. df.loc[1:3] gives three rows; df.iloc[1:3] gives two.
Your turn: pull out the first city by position, the temperature of the row labelled 2 by label, and the first two rows.
You start from this, and edit it in the browser:
import pandas as pd
df = pd.DataFrame({
"city": ["London", "Lisbon", "Oslo", "Tokyo"],
"temp": [14, 24, 3, 19],
})
# Set first_city, temp_at_2 and first_two_cities (a list of city names).