Lesson 9 of 23
❮Prev Next❯

PY-401 · pandas basics

Selecting rows and columns

⏱ 8 min 🐍 Real Python 3 🎬 Animated

9of 23

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    ⚡ The 30-second answer

    Use df["col"] for one column and df[["a", "b"]] for several. For rows, df.loc[...] selects by label and df.iloc[...] selects by position, and both take a row and a column: df.loc["B1", "price"]. The rule to remember: loc means labels, iloc means integer positions.

    • Select one or several columns
    • Select rows by label with loc
    • Select rows by position with iloc

    Try it

    Watch it come alive, run it yourself, then prove it. Real Python, right on this page.

    Watch Python run the example. Every variable is a jar; watch the values change and the output appear.

    Selecting rows and columns, running
    1. import pandas as pd
    2. df = pd.DataFrame({
    3. "product": ["Tea", "Coffee", "Cake", "Juice"],
    4. "units": [12, 7, 4, 9],
    5. "price": [2.5, 3.0, 4.5, 2.0],
    6. }, index=["A1", "A2", "B1", "B2"])
    7. print(df["product"].tolist())
    8. print(df[["product", "price"]])
    9. print(df.loc["B1"])
    10. print(df.iloc[0, 1])
    11. print(df.loc["A2":"B1", "units"].tolist())
    Press ▶ to watch Python run this, one line at a time.
    1. The problemA stock list has a product code on every row. The warehouse asks for the price of item B1 and the units of the first item on the list. One is a label, one is a position, and pandas has a tool for each.
    2. The Python ideadf["col"] # one columnUse df["col"] for one column and df[["a", "b"]] for several.
    3. In real lifeA hotel booking table is indexed by room number. Reception reads one room with bookings.loc[214], while a report takes the 10 most recent rows with bookings.iloc[-10:].

    Start with a question

    A stock list has a product code on every row. The warehouse asks for the price of item B1 and the units of the first item on the list. One is a label, one is a position, and pandas has a tool for each.

    Every question you ask a table starts with picking the right rows and columns. Getting loc and iloc right avoids silent wrong answers.

    Explain it like I'm 10

    loc is finding a house by its name on the gate. iloc is finding it by counting: the third house on the street. Both get you to a house, in different ways.

    The technical explanation

    df["product"] gives one column as a Series. Double brackets, df[["product", "price"]], give a smaller DataFrame.

    df.loc["B1"] is the row labelled B1. df.loc["B1", "price"] is one cell.

    df.iloc[0] is the first row whatever its label. df.iloc[0, 1] is row 0, column 1.

    Both accept slices and lists: df.loc["A2":"B1", "units"] or df.iloc[:2, [0, 2]].

    lociloc
    Selects byLabel (name)Position (0, 1, 2 …)
    Slice endIncludedExcluded
    Exampledf.loc["B1", "price"]df.iloc[2, 2]

    Syntax

    df["col"]            # one column
    df[["a", "b"]]       # several columns
    df.loc[row_label, col_label]
    df.iloc[row_pos, col_pos]

    ▶ Run the example 🎬 Watch it come alive

    Real-world scenario

    A hotel booking table is indexed by room number. Reception reads one room with bookings.loc[214], while a report takes the 10 most recent rows with bookings.iloc[-10:].

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. Which selects by label?
    2. 2. df[["a", "b"]] returns…
    3. 3. df.iloc[0, 1] is…
    4. 4. Does df.loc["A2":"B1"] include row B1?
    5. 5. Does df.iloc[0:2] include position 2?

    Questions people ask

    What is the difference between loc and iloc in pandas?

    loc selects rows and columns by their labels and includes the end of a slice. iloc selects by integer position and excludes the end of a slice, like normal Python indexing.

    Why do I get a SettingWithCopyWarning in pandas?

    You probably changed a value on a selection made in two steps, such as df[df.x > 1]["y"] = 0, which may change a temporary copy. Do it in one step with df.loc[df.x > 1, "y"] = 0.

    Interview questions

    How this topic comes up in Python interviews. Answer out loud first, then open the model answer.

    beginner What is the difference between loc and iloc in pandas?

    loc selects rows and columns by their labels and includes the end of a slice. iloc selects by integer position and excludes the end of a slice, like normal Python indexing.

    beginner Why do I get a SettingWithCopyWarning in pandas?

    You probably changed a value on a selection made in two steps, such as df[df.x > 1]["y"] = 0, which may change a temporary copy. Do it in one step with df.loc[df.x > 1, "y"] = 0.

    intermediate Which selects by label?

    loc. loc uses labels; iloc uses integer positions.

    intermediate df[["a", "b"]] returns…

    A DataFrame with columns a and b. A list of names in the brackets gives a smaller DataFrame.

    Quick revision

    Remember

    • Select one or several columns
    • Select rows by label with loc
    • Select rows by position with iloc
    • A loc slice includes the end label ("A2":"B1" keeps B1), but an iloc slice stops before the end position, like normal Python.

    Syntax

    df["col"]            # one column
    df[["a", "b"]]       # several columns
    df.loc[row_label, col_label]
    df.iloc[row_pos, col_pos]

    Official documentation