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:
It starts with one row, one sample. pandas reaches it two ways: iloc counts positions from 0, like a list; loc uses its label:
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: int64Add 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
MediumA 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.
- Print who finished at that place.
- Print their time.
- Print who finished last.
For a different race and the place 2:
Place 2: Ola Berg
Time: 51.5 minutes
Last: Kim ItoTry it yourself
import pandas as pd
race = pd.read_csv("race.csv")
place = int(input())
# Write your code below
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Data and Plots
2NumPy Arrays
Creating ArraysShape and SizeRanges of NumbersIndexing and SlicingRecap: Temperature GridPractice on your own: Online Python compiler