Selecting Columns and Rows

loc goes by label, iloc goes by position, and the difference matters.

Columns by name

One name gives a Series; a list of names gives a smaller DataFrame. The double brackets are a list inside the brackets, not special syntax.

import pandas as pd

df = pd.DataFrame({"name": ["Ada", "Grace"], "score": [92, 88]})
print(df["score"])
print(df[["name", "score"]])

Rows by label or by position

loc reads the index label, iloc reads the position. They agree on a default index and disagree the moment you sort or filter, which is exactly when the bug appears.

import pandas as pd

df = pd.DataFrame({"score": [92, 88, 79]}, index=["a", "b", "c"])
print(df.loc["b", "score"])
print(df.iloc[1]["score"])

Exercise

Try It Yourself

Write score_for(df, name) that returns the score belonging to name, where the table has a name column and a score column.

Press Run to see output

Check Your Understanding