Menu
CoddyTech

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:

The players table in its original order on the left and, after an arrow, sorted by points from 31 down to 8 on the right; every row keeps its label, and the top two, Ben and Dee, are marked head(2)

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      22

The 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 icon

Challenge

Medium

An 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:

  1. The n rows with the largest values in that column, largest first.
  2. 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: Mosaic

Try 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']}")
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