🎓 A1Learner
🔍
0 of 50 lessons completed

Rows by Label: loc

loc selects rows and columns by label. A label is a name, like a day of the week or a column name.

One row by label

loc with the label Tue picks the Tuesday row.

import pandas as pd

df = pd.DataFrame({
    "product": ["Tea", "Coffee", "Mug"],
    "units": [2, 1, 3],
}, index=["Mon", "Tue", "Wed"])
print(df.loc["Tue"])

Rows and columns together

A list of row labels and a list of column names pick a small table.

import pandas as pd

df = pd.DataFrame({
    "product": ["Tea", "Coffee", "Mug"],
    "units": [2, 1, 3],
}, index=["Mon", "Tue", "Wed"])
print(df.loc[["Mon", "Wed"], ["product", "units"]])

A slice by label includes both ends

The slice Mon to Tue gives both rows. The end label is included.

import pandas as pd

df = pd.DataFrame({
    "product": ["Tea", "Coffee", "Mug"],
    "units": [2, 1, 3],
}, index=["Mon", "Tue", "Wed"])
print(df.loc["Mon":"Tue"])

Example

import io
import pandas as pd

SALES_CSV = """order_id,date,product,category,units,price,region
101,2026-01-05,Tea,Drink,2,4.50,North
102,2026-01-06,Coffee,Drink,1,6.00,South
103,2026-01-07,Mug,Home,3,12.00,East
104,2026-01-08,Notebook,Office,2,8.50,West
105,2026-01-09,Pen,Office,5,2.00,North
106,2026-01-12,Lamp,Home,1,24.00,South
107,2026-01-13,Tea,Drink,4,4.50,East
108,2026-01-14,Coffee,Drink,2,6.00,West
109,2026-01-15,Mug,Home,1,12.00,North
110,2026-01-16,Notebook,Office,3,8.50,South
111,2026-01-19,Pen,Office,2,2.00,East
112,2026-01-20,Lamp,Home,2,24.00,West"""

sales = pd.read_csv(io.StringIO(SALES_CSV))
print(sales.loc[0:2, ["product", "units"]])

Key points

  • Use loc with a row label to get one row.
  • Use loc with a row label and a column name to get one value.
  • A list of labels picks several rows.
  • A label slice includes both ends, so "Mon":"Tue" gives two rows.
  • Row labels live in the index, the leftmost column of the table.
  • loc picks by name, never by counting from zero.

In this example, the sales table is read from the CSV text. loc picks rows 0, 1, and 2 by label. The label slice includes row 2. Only the product and units columns are kept.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does df.loc["Tue"] return?