Menu
CoddyTech

Selecting Rows

Part of the Data and Plots section of Coddy's Machine Learning journey. Lesson 37 of 60.

This chapter ends with a shop's best sellers, picked like this:

A shop's table of six products with their category and revenue, the kitchen rows faded, and an arrow to the top 3 garden products by revenue: Hose 1500, Seeds 800, Rake 600

It starts with one row, one sample. pandas reaches it two ways: iloc counts positions from 0, like a list; loc uses its label:

The planets table drawn as a grid, its rows labelled Mercury, Earth, Mars and Jupiter, with positions 0 to 3 beside them; the Earth row is marked loc Earth, by label, and the Mars row iloc 2, by position

planets = pd.DataFrame(
    {"moons": [0, 1, 2, 95], "diameter_km": [4879, 12756, 6792, 142984]},
    index=["Mercury", "Earth", "Mars", "Jupiter"],
)
print(planets.iloc[2])
print(planets.loc["Earth"])

This prints two rows, each a Series labelled by the columns:

moons             2
diameter_km    6792
Name: Mars, dtype: int64
moons              1
diameter_km    12756
Name: Earth, dtype: int64

Add a column name for one cell: planets.loc["Jupiter", "moons"] is 95. iloc[-1] is the last row.

In a table read from a CSV file, labels match positions until rows are filtered or sorted.

challenge icon

Challenge

Medium

A 10 km race's results are in race.csv, one runner per row in finishing order, with the columns runner, club and minutes. The program loads it into race and reads a place, where 1 is the winner.

  1. Print who finished at that place.
  2. Print their time.
  3. Print who finished last.

For a different race and the place 2:

Place 2: Ola Berg
Time: 51.5 minutes
Last: Kim Ito

Try it yourself

import pandas as pd

race = pd.read_csv("race.csv")
place = int(input())

# Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Data and Plots

Practice on your own: Online Python compiler