Count Unique Elements in pandas DataFrame Column in Python (Example Code)
In this Python tutorial you’ll learn how to get the number of unique elements in a pandas DataFrame variable.
Setting up the Example
import pandas as pd # Import pandas library |
import pandas as pd # Import pandas library
my_df = pd.DataFrame({'A':[7, 7, 4, 1, 2, 8, 2], # Construct example DataFrame in Python 'B':range(1, 8)}) print(my_df) # Display example DataFrame in console # A B # 0 5 1 # 1 7 2 # 2 4 3 # 3 1 4 # 4 2 5 # 5 8 6 # 6 2 7 |
my_df = pd.DataFrame({'A':[7, 7, 4, 1, 2, 8, 2], # Construct example DataFrame in Python 'B':range(1, 8)}) print(my_df) # Display example DataFrame in console # A B # 0 5 1 # 1 7 2 # 2 4 3 # 3 1 4 # 4 2 5 # 5 8 6 # 6 2 7
Example: Get Count of Unique Values in Particular pandas DataFrame Variable
print(my_df['A'].nunique()) # Count unique values in column # 5 |
print(my_df['A'].nunique()) # Count unique values in column # 5