Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Data Foundations · A little practice goes a long way.

← Inspect lessonsTINY TABLES · REAL PYTHON · YOUR PACE
Selecting data · I09 · 8 MIN

Rows and columns by label

Select named rows and columns with loc.

Exercises within this concept

  1. FollowFollow the techniqueCurrent exercise
  2. ChangeAdapt a requirement
  3. TransferChoose and combine

Understand the idea

loc selects labels, not positions. Use a slice for a continuous range and a list for specific labels.

Concept sketch: loc: labels B–D, only pricelabelnamepriceAMilo2BLuna4CRex3DPip5loc: labels B–D, only price
Illustration · not the exercise output

A small example

With labels A, B, C, D, E: loc["B":"D"] selects B, C, D; loc[["D", "B"]] selects D, then B.

Follow the code

Apply the idea to the supplied table. Read from top to bottom; the final line displays the result.

df.loc["B":"D", ["price"]]

What each part does

df.loc["B":"D", ["price"]]
labels B through D, including D; one price column
Other choices for later exercises
df.iloc[1:4, [2]]
positions 1, 2 and 3; column at position 2

Your inputs

The editable setup on the right creates df and the additional inputs shown below. Run executes the setup and your work from top to bottom.

Candy shop · 6 synthetic rows
rowcandyflavourpriceratingshelf
AGummy Bearfruity1.24.1A
BChoco Popchocolate2.14.6B
CMint Bitemint1.53.8A
DBerry Loopfruity2.84.4B
ECocoa Cubechocolate3.44.9A
FLemon Dropfruity1.84B

Your task · Follow

  1. Using df, return labels B through D, including the end label, keeping only price as a one-column DataFrame.
  2. Use: loc.
Hint

A label slice includes its ending label. Keep the column name in a list for a DataFrame.

Reveal solution

One way to do it. Keep any supplied setup in the editor and use this in the Your work section.

df.loc["B":"D", ["price"]]
Your task · Follow
  1. Using df, return labels B through D, including the end label, keeping only price as a one-column DataFrame.
  2. Use: loc.

Tab: indent · Shift+Tab: outdent · Esc, then Tab: leave editor

Edit Python. Control or Command plus Enter runs it. Tab indents by four spaces. Shift plus Tab outdents. Press Escape, then Tab or Shift plus Tab to leave the editor.

Each run executes all editor code in a fresh Python session. Display a value by leaving it on the final line.

Python starts when you open a lesson.

Output

Run your code to see what Python returns.