You can use the value_counts() function in pandas to count the occurrences of values in a given column of a DataFrame.
You can use one of the following methods to sort the results of the value_counts() function:
Method 1: Sort Counts in Descending Order (Default)
df.my_column.value_counts()
Method 2: Sort Counts in Ascending Order
df.my_column.value_counts().sort_values()
Method 3: Sort Counts in Order They Appear in DataFrame
df.my_column.value_counts()[df.my_column.unique()]
The following examples show how to use each method in practice with the following pandas DataFrame:
import pandas as pd #create DataFrame df = pd.DataFrame({'team': ['A', 'A', 'B', 'B', 'B', 'B', 'B', 'C'], 'points': [15, 12, 18, 20, 22, 28, 35, 40]}) #view DataFrame print(df) team points 0 A 15 1 A 12 2 B 18 3 B 20 4 B 22 5 B 28 6 B 35 7 C 40
Example 1: Sort Counts in Descending Order
The following code shows how to count the occurrences of each unique value in the team column and sort the counts in descending order:
#count occurrences of each value in team column and sort in descending order df.team.value_counts() B 5 A 2 C 1 Name: team, dtype: int64
Notice that the counts are sorted in descending order by default.
Example 2: Sort Counts in Ascending Order
The following code shows how to count the occurrences of each unique value in the team column and sort the counts in ascending order:
#count occurrences of each value in team column and sort in ascending order df.team.value_counts().sort_values() C 1 A 2 B 5 Name: team, dtype: int64
Notice that the counts are now sorted in ascending order, i.e. smallest to largest.
Example 3: Sort Counts in Order they Appear in DataFrame
The following code shows how to count the occurrences of each unique value in the team column and sort the counts in order in which the unique values appear in the DataFrame:
#count occurrences of each value in team column and sort in order they appear df.team.value_counts()[df.team.unique()] A 2 B 5 C 1 Name: team, dtype: int64
Notice that the counts are now sorted based on the order in which the unique values appear in the DataFrame.
For example, the value ‘A’ occurs first in the team column, then ‘B’ occurs, then ‘C’ occurs.
Thus, this is the order in which the counts appear in the output.
Additional Resources
The following tutorials explain how to perform other common tasks in pandas:
Pandas: How to Plot Value Counts
Pandas: How to Use GroupBy and Value Counts
Pandas: How to Represent value_counts as Percentage