Introduction
In this tutorial, we want to count and get the unique values in a column of a Pandas DataFrame. In order to do this, we use the the nunique() method and the unique() method of Pandas.
Import Libraries
First, we import the following python modules:
import pandas as pd
Create Pandas DataFrame
Next, we create a Pandas DataFrame with some example data from a dictionary:
mydict = {
"column1": [3, 4, 7, 8, 1],
"column2": [11.3, 12.5, 0.4, 0.77, 9.4],
"column3": ["AI", "AI", "DL", "Python", "AI"],
}
df = pd.DataFrame(mydict)
df
Count Unique Values
Now, we would like to get the number of unique values in column "column3" of the DataFrame.
To do this, we use the nunique() method of Pandas:
num_unique_values = df["column3"].nunique()
print(f"Number of unique values: {num_unique_values}")
Get Unique Values
Next, we would like to get the unique values in column "column3" of the DataFrame.
To do this, we use the unique() method of Pandas:
unique_values = df["column3"].unique()
print(f"Unique values: {unique_values}")
Conclusion
Congratulations! Now you are one step closer to become an AI Expert. You have seen that it is very easy to count and get the unique values in a column of a Pandas DataFrame. We can simply use the nunique() method and the unique() method of Pandas. Try it yourself!
Also check out our Instagram page. We appreciate your like or comment. Feel free to share this post with your friends.