Sorting Values
Part of the Data and Plots section of Coddy's Machine Learning journey. Lesson 39 of 60.
Who scored the most? Sorting answers at a glance. .sort_values("col") orders the rows by a column, smallest first; ascending=False puts the largest first:
players = pd.DataFrame({
"player": ["Ada", "Ben", "Cy", "Dee", "Eli"],
"points": [14, 31, 8, 22, 17],
})
top = players.sort_values("points", ascending=False)
print(top.head(2))This prints the top 2:
player points
1 Ben 31
3 Dee 22The rows took their labels along: Ben keeps label 1. So the first row of top is top.iloc[0], while top.loc[0] is still Ada.
sort_values returns a new table and leaves players as it was, so keep the result in a variable.
Challenge
MediumAn app store lists apps in apps.csv, with the columns app, downloads_k (thousands) and rating. The program reads a column name and a number n, then should print:
- The
nrows with the largest values in that column, largest first. Lowest:and the app with the smallest value.
The starter has two sorting mistakes. Fix both. For a different store, rating and n = 2:
app downloads_k rating
2 PetPal 88 4.9
0 Zipline 512 4.5
Lowest: MosaicTry it yourself
import pandas as pd
apps = pd.read_csv("apps.csv")
column = input()
n = int(input())
# This code prints the wrong answers: fix it
apps.sort_values(column, ascending=False)
print(apps.head(n))
lowest = apps.sort_values(column, ascending=False)
print(f"Lowest: {lowest.iloc[0]['app']}")
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