You can use the following methods to sort the rows or columns in a pandas crosstab:
Method 1: Sort Crosstab by Row Values
pd.crosstab(df.col1, df.col2).sort_index(axis=0, ascending=False)
Method 2: Sort Crosstab by Column Values
pd.crosstab(df.col1, df.col2).sort_index(axis=1, ascending=False)
The following examples show how to use each of these methods in practice with the following pandas crosstab:
import pandas as pd #create DataFrame df = pd.DataFrame({'team': ['A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C'], 'position':['G', 'G', 'F', 'G', 'F', 'F', 'F', 'G', 'G', 'F', 'F'], 'points': [22, 25, 24, 39, 34, 20, 18, 17, 20, 19, 22]}) #create crosstab to display count of players by team and position my_crosstab = pd.crosstab(df.team, df.position) #view crosstab print(my_crosstab) position F G team A 1 2 B 3 1 C 2 2
Example 1: Sort Crosstab by Row Values
We can use the following syntax to sort the rows of the crosstab based on the values in the team column in descending order (from Z to A):
#create crosstab with rows sorted from Z to A pd.crosstab(df.team, df.position).sort_index(axis=0, ascending=False) position F G team C 2 2 B 3 1 A 1 2
Notice that the rows of the crosstab are now sorted based on the team values in reverse alphabetical order.
Note: The crosstab() function displays the row values of the crosstab in alphabetical order (from A to Z) by default.
Example 2: Sort Crosstab by Column Values
We can use the following syntax to sort the columns of the crosstab based on the values in the team column in descending order (from Z to A):
#create crosstab with columns sorted from Z to A pd.crosstab(df.team, df.position).sort_index(axis=1, ascending=False) position G F team A 2 1 B 1 3 C 2 2
Notice that the columns of the crosstab are now sorted based on the position values in reverse alphabetical order.
Note: The crosstab() function displays the column values of the crosstab in alphabetical order (from A to Z) by default.
Note: You can find the complete documentation for the pandas crosstab() function here.
Additional Resources
The following tutorials explain how to perform other common tasks in pandas:
Pandas: How to Create Crosstab with Percentages
Pandas: How to Use aggfunc in crosstab() Function
Pandas: How to Create Bar Plot from Crosstab