The value_counts() function in pandas is used to count the unique values in a Series. It returns a Series containing counts of unique values in descending order. Here's how it works:
Syntax
Series.value_counts(normalize=False, sort=True, ascending=False, bins=None, dropna=True)
Parameters
- normalize: If
True, the result will contain the relative frequencies of the unique values. - sort: If
True, the result will be sorted in descending order. - ascending: If
True, the result will be sorted in ascending order. - bins: If specified, it will bin the values into discrete intervals.
- dropna: If
True, it will excludeNaNvalues from the counts.
Example
import pandas as pd
# Creating a sample Series
data = pd.Series(['apple', 'banana', 'apple', 'orange', 'banana', 'banana'])
# Using value_counts
counts = data.value_counts()
print(counts)
Output
banana 3
apple 2
orange 1
dtype: int64
In this example, value_counts() counts how many times each fruit appears in the Series.
