Find the Smallest Values of a ColumnFind the Smallest Values of a Column

We will learn another crucial function, which outputs the top smallest or largest values. You already know that we can sort values and then extract a specific number of rows. Unsurprisingly, pandas can do so using only one line of code. Look at the example of how to retrieve the oldest five cars:

If you want to sort by one column and then by another, just put a list with column names in the necessary order. Look at the example where we will sort firstly by 'Year' and then by 'Engine_volume'. This code will first extract the 5 oldest cars, and then if the years match, the car with the lesser value of the 'Engine_volume' column will take priority:

Try to compare the two examples below. Now we will advance the function a little bit. Let's return our examples with the column's 'Year' values. In our column, the 'Year' values can be repeated, so if we want to output the ten oldest cars with the previous syntax, our function will take just ten values. It doesn't care if the 11th or 12th value is the same as the 10th. We can put the argument keep = 'all' into the .nsmallest() function to prevent such cases. Look at the example, and try to execute it to see the difference:


Finally, it's time to practice! Here, you should follow this algorithm:

  1. Retrieve data on cars where the column 'Year' values are greater than 2010.
  2. Extract the cheapest 15 cars (the top 15 values of the column 'Price'). Include all duplicated values of the column 'Price'.
  3. Output all values of the data set data_cheapest.

Everything was clear?

Section 3. Chapter 5
toggle bottom row