loc

noun

say it: “LOHK” /ˈloʊk/

In pandas, the way to pick rows and columns of a table by their labels, such as a product code and a column name.

What does loc do in pandas?

loc picks rows and columns by their labels, written df.loc[rows, columns], such as a product's SKU and a column's name. A slice of labels includes its end. Because labels move with their rows, loc finds the same row even after a sort.

catalog = products.set_index("sku")
print(catalog.loc["TO-1042", "price"])                    # one product's price
print(catalog.loc["TO-1001":"TO-1004", ["product", "price"]])   # four rows, TO-1004 included

In a sentence

  • “The slice in loc included its last label, TO-1004.”
  • “loc found product TO-1042 by its SKU, wherever the sort had moved it.”

Level: Journeyman · More Python terms at this level

Updated