Series.value_counts() - Pandas Series
The Series.value_counts()
method is used to count the number of occurrences of each unique value in a Pandas Series. It returns a new Series with the counts of unique values in descending order.
Syntax
The syntax for using the Series.value_counts()
method is:
series.value_counts(normalize=False, sort=True, ascending=False, bins=None, dropna=True)
where
normalize
(bool): IfTrue
, returns the relative frequency (proportions) of the unique values. Default isFalse
.sort
(bool): Sorts by value. Default isTrue
.ascending
(bool): Sort order. Default isFalse
.bins
(int): Used only with numeric data. Groups the values into half-open bins. Applies only to numerical columns. Default isNone
.dropna
(bool): Excludes missing values. Default isTrue
.
Example
Consider the following example:
import pandas as pd
fruits = pd.Series(["apple", "orange", "apple", "banana", "banana", "orange", "apple"])
counts = fruits.value_counts()
print(counts)
Output:
apple 3
orange 2
banana 2
dtype: int64
In this example, a Pandas series named fruits
is created with some values. The value_counts()
method is called on this series to get the count of unique values. The resulting series, named counts
, is then printed to the console.
Explanation
The value_counts()
method returns a new Pandas series with the counts of each unique value in the original series. In the example above, the apple
value occurs 3 times, orange
occurs twice, and banana
occurs twice. The resulting new series is sorted in descending order by the number of occurrences of each value.
Use
The value_counts()
method is useful for determining the number of occurrences of each unique value in a Pandas series. This can be useful for analyzing data and identifying trends.
Important Points
- The
Series.value_counts()
method returns a new Pandas series with the counts of each unique value in the original series. - The new series is sorted in descending order by the number of occurrences of each value.
- The method has several optional parameters that allow for more control over the results.
Summary
The Series.value_counts()
method is a powerful tool for analyzing data in a Pandas series. Its ability to count the number of occurrences of each unique value, along with its optional parameters, make it a valuable asset in data analysis and manipulation.