We can use the value_counts() function to get the count of unique records for all the unique values in a column of a DataFrame. Let’s take the example of the iris dataset. Let’s first read the dataset from a CSV file and print the first few lines of the dataset.
import pandas df = pandas.read_csv("iris.csv") print(df.head())
The output is:
sepal_length sepal_width petal_length petal_width species 0 5.1 3.5 1.4 0.2 setosa 1 4.9 3.0 1.4 0.2 setosa 2 4.7 3.2 1.3 0.2 setosa 3 4.6 3.1 1.5 0.2 setosa 4 5.0 3.6 1.4 0.2 setosa
So, it looks like the dataset contains the sepal length, sepal width, petal length, and petal width of some flowers. And based on these features, we can find out the type of flowers. Now, let’s say we want to find out the unique values present in the species column. We have already discussed in our previous article, we can use the unique() function for that purpose.
import pandas df = pandas.read_csv("iris.csv") print(df.head()) print("Unique species: \n", df["species"].unique())
The output is:
0 Comments