Understand the idea
loc selects labels, not positions. Use a slice for a continuous range and a list for specific labels.
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.
| row | candy | flavour | price | rating | shelf |
|---|---|---|---|---|---|
| A | Gummy Bear | fruity | 1.2 | 4.1 | A |
| B | Choco Pop | chocolate | 2.1 | 4.6 | B |
| C | Mint Bite | mint | 1.5 | 3.8 | A |
| D | Berry Loop | fruity | 2.8 | 4.4 | B |
| E | Cocoa Cube | chocolate | 3.4 | 4.9 | A |
| F | Lemon Drop | fruity | 1.8 | 4 | B |
Your task · Follow
- Using df, return labels B through D, including the end label, keeping only price as a one-column DataFrame.
- 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"]]