Mastering Sorting Values within Pandas DataFrame
Topic Overview and Actualization
Today, we will explore sorting within a DataFrame using Python's pandas. We will delve into the sort_values() function, covering single and multi-column sorting and handling missing values.
Sample Dataset
Let's consider this small dataset containing statistics of basketball players:
Note that there is a tie in Points between "K. Durant" and "K. Bryant".
Learning How to Sort
We can sort DataFrame values using the sort_values() function.
In this example, the DataFrame is sorted by column Points in descending order using the by and ascending parameters. Thus, we can list the most successful players in terms of average points scored.
Sorting by Multiple Columns
In the previous example, pandas resolves a tie between "K. Durant" and "K. Bryant" by index, putting the player with the lower index first. Do you agree that a more reasonable decision would be to resolve ties by other players' characteristics – for example, putting players with higher Assists scores first?
It is possible by providing multiple sorting columns.
In this example, the DataFrame is sorted by column Points and any ties are resolved by the column Assists.
Sorting by Multiple Columns in Different Order
Let's alter the behavior and handle ties by sorting players alphabetically:
As ascending=False, player names' sorting is also descending, which results in reverse alphabetical order. To fix it we can pass two values to ascending, defining behavior of sorting differently for 'Points' and 'Player':
'Points' sorting is still in descending order, but 'Player' sorting is in ascending.
