📜  Pandas Series.value_counts()(1)

📅  最后修改于: 2023-12-03 15:03:28.554000             🧑  作者: Mango

Pandas Series.value_counts()

The value_counts() function in Pandas Series returns a Series containing counts of unique values in a Series. It counts the occurrence of each unique value and arranges them in descending order.

Syntax
Series.value_counts(normalize=False, sort=True, ascending=False, bins=None, dropna=True)
Parameters
  • normalize: If set to True, it normalizes the output values to represent percentages.
  • sort: If set to True, sorts the resulting Series by values.
  • ascending: If set to True, sorts the resulting Series in ascending order.
  • bins: Specifies the number of equal-width bins to use when counting values.
  • dropna: If set to False, it includes the count of missing/null values in the result.
Returns

The result of value_counts() is a Series with unique values as the index and their corresponding counts as values. The index is sorted by default in descending order of counts.

Example
import pandas as pd

# Create a Series
series = pd.Series([1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5])

# Get the value counts
value_counts = series.value_counts()

print(value_counts)

Output:

5    5
4    4
3    3
2    2
1    1
dtype: int64

In the above example, the value_counts() function counts the occurrence of each unique value in the Series and returns a new Series with the counts. It shows that the value 5 appears 5 times, 4 appears 4 times, 3 appears 3 times, 2 appears 2 times, and 1 appears 1 time.

Use Cases
  • Finding the frequency distribution of categorical variables
  • Identifying the most common values in a Series
  • Detecting outliers or uncommon values in a dataset

For a more detailed explanation and additional methods provided by the Pandas Series object, you can refer to the official Pandas documentation.