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
locslices are inclusive of the end label.ilocslices behave like Python lists, end exclusive.- Both take a row selector and a column selector.
Keywords and builtins used here
asprint
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.
Step 2 of 4 in Selecting rows, step 6 of 26 in pandas.