typestar

loc and iloc in Python

loc works in labels, iloc in positions — and mixing them is the classic bug.

import pandas as pd

frame = pd.DataFrame(
    {"tpm": [91, 104, 88, 97], "stars": [1, 3, 2, 3]},
    index=["mon", "tue", "wed", "thu"])

print(frame.loc["tue"])
print(frame.loc["mon":"wed", "tpm"])
print(frame.iloc[0:2])
print(frame.iloc[-1, 1], frame.at["thu", "stars"])

How it works

  1. loc slices are inclusive of the end label.
  2. iloc slices behave like Python lists, end exclusive.
  3. Both take a row selector and a column selector.

Keywords and builtins used here

The run, in numbers

Lines
10
Characters to type
265
Tokens
126
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 72 seconds.

Type this snippet

Step 2 of 4 in Selecting rows, step 6 of 26 in pandas.

← Previous Next →