Start learning free

LESSON 13 OF 165 · MACHINE LEARNING: PANDAS

Sort and Take the Top in Python

Practice

"Who are our best customers?" is a sort and a cut. df.sort_values("visits") gives back a new DataFrame with the same rows in a new order, from the smallest visits up. Add ascending=False to put the biggest first. Then .head(5) keeps the first 5 rows of the sorted table.

loyal = df.sort_values("visits", ascending=False)
print(loyal[["customer_id", "visits"]].head(3).to_string())

Each row keeps its label from df, so the labels on the left show where a row sat before the sort. A blank value (NaN) goes to the end of a sort, whichever way you sort.

Give sort_values a list of columns to sort by two things: df.sort_values(["visits", "days_since_last"], ascending=False) sorts by visits, and only rows with the same visits are put in order by days_since_last. And df.nlargest(3, "visits") gives back the 3 rows with the biggest visits, biggest first: a sort and a head in one call, with blanks left out.

Your script must print these three tables:

     customer_id    city   age  orders  spent
0              1    Rome  52.0       6    720
62            63  Berlin  37.0       4    666
73            74   Porto  46.0       6    665
157          158    Cluj   NaN       5    655
153          154    Cluj  30.0       5    598
     customer_id    city   age  orders  spent
71            72   Porto  29.0       9    505
260          261  Madrid  63.0       8    390
52            53    Lyon  52.0       7    505
176          177  Madrid  18.0       7    502
241          242   Porto  22.0       7    459
     customer_id    city   age  orders  spent
205          206  Madrid  67.0       1     39
109          110    Lyon  64.0       3     66
260          261  Madrid  63.0       8    390

Your task: df and the list of column names cols are already there. Sort the customers by spent, biggest first, into top, and by orders and then spent, biggest first, into busy; print the cols columns of the first 5 rows of each. Then take the 3 oldest customers with nlargest into oldest and print its cols columns.


Assignment
Follow the Coding Tutorial to sort the customers by spent, by orders and spent, and to take the 3 oldest.


Hint
sort_values goes from the smallest up unless you pass ascending=False. With a list of columns, the second one only matters for rows that tie on the first.


STEP 1 OF 6
    Ctrl + Enter to check

    Pd Sort in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free