For more information on concepts covered in this lesson, you can check out Introduction to Sorting Algorithms in Python.
Sorting Your DataFrame on a Single Column
Sorting Your DataFrame on a Single Column. To sort the DataFrame based on the values in a single column, you’ll use
.sort_values(). By default, this will return a new DataFrame sorted in ascending order.
It doesn’t modify the original DataFrame. To use
.sort_values(), you pass a single argument to the method containing the name of the column you want to sort by. In this example, you sort the DataFrame by the
city08 column, which represents city miles per gallon for fuel-only cars.
Another parameter of
ascending, which by default is set to
True. If you want the DataFrame sorted in descending order, then you can pass
False to this parameter, as seen on-screen.
Looking at the highlighted indices, you can see the rows are in a different order. This is because
quicksort is not a stable sorting algorithm, but
mergesort is. Note that in pandas,
kind is ignored when you sort on more than one column or label.
02:52 When you’re sorting multiple records that have the same key, a stable sorting algorithm will maintain the original order of those records after sorting. For that reason, using a stable sorting algorithm is necessary if you plan to perform multiple sorts.
Become a Member to join the conversation.