Pandas pd.value_counts() function
pd.value_counts() is a function in the Pandas library used toCount the frequency of each valuefunction. It computes how many times each unique value appears in an array and returns the result sorted in descending order of frequency.
This is one of the most commonly used functions in categorical data analysis; it gives you a quick overview of the data distribution, such as vote counts or product category distributions.
Word meaning: value_counts It means "count values", that is, counting how many times each value appears.
Basic syntax and parameters
pd.value_counts() It is a top-level function of the Pandas library used to compute the frequency of each unique value.
Syntax format
pd.value_counts(values, sort=True, ascending=False, normalize=False, bins=None, dropna=True)
Parameter Description
- Parameters:
values - Type: Series or array-like object.
- Description: The data whose frequencies you want to count. Usually a Series.
- Parameters:
sort - Type> boolean.
- Whether to sort by frequency. Defaults to
True(in descending order of frequency).
- Parameters:
ascending - Type: boolean.
- If it is
True, sort in ascending order of frequency; ifFalse(the default), sort in descending order of frequency.
- Parameters:
normalize - Type: boolean.
- If it is
True, return the proportion of each value (between 0 and 1) instead of the absolute frequency. Defaults toFalse。
- Parameters:
bins - Type: int or None.
- If an integer is given, bin the numeric data and then count frequencies (similar to a histogram). Not suitable for categorical data.
- Parameters:
dropna - Type: boolean.
- Whether to include NaN in the result. Defaults to
True(excluded).
Function description
- Return Value: Returns a Series whose index is the unique values and whose values are the frequencies (or proportions).
- effect: Count and display how many times each unique value appears.
Example
Let us thoroughly master pd.value_counts() through a series of examples from simple to complex.
Example 1: Basic usage - counting frequencies of categorical data
Example
import
pandas
as
pd
import
numpy
as
np
1. Creating a Series with duplicate values
colors
=
pd.
Series
(
[
'red'
,
'blue'
,
'green'
,
'red'
,
'blue'
,
'yellow'
,
'red'
,
'blue'
,
'blue'
]
)
(
"=== Original Series ==="
)
(
colors
)
2. Use pd.value_counts() to count frequencies
result
=
pd.
value_counts
(
colors
)
(
"\n=== pd.value_counts() frequency count ==="
)
(
result
)
Expected output:
=== 原始 Series ===
0 red
1 blue
2 green
3 red
4 blue
5 yellow
6 red
7 blue
8 blue
dtype: object
=== pd.value_counts() 频次统计 ===
blue 4
red 3
green 1
yellow 1
dtype: int64
Code analysis:
- The result is sorted in descending order of frequency: blue appears most often (4 times), followed by red (3 times), while green and yellow appear once each.
- It returns a Series whose index holds the color values and whose values hold the counts.
Example 2: Using the normalize parameter to compute proportions
normalize=True You can convert frequencies into proportions to see the relative distribution of the data more easily.
Example
import
pandas
as
pd
import
numpy
as
np
Create voting data
votes
=
pd.
Series
(
[
'A'
,
'B'
,
'A'
,
'C'
,
'A'
,
'B'
,
'A'
,
'A'
,
'C'
,
'B'
,
'A'
,
'B'
]
)
(
"=== Voting data ==="
)
(
votes
)
1. Absolute frequencies
(
"\n=== Absolute frequencies ==="
)
(
pd.
value_counts
(
votes
)
)
2. Relative proportions (normalize=True)
(
"\n=== Relative proportions ==="
)
result_normalized
=
pd.
value_counts
(
votes
,
normalize
=
True
)
(
result_normalized
)
(
f
"\nSum of proportions: {result_normalized.sum():.2f}"
)
3. Sort in ascending order
(
"\n=== Ascending order ==="
)
(
pd.
value_counts
(
votes
,
ascending
=
True
)
)
Expected output:
=== 投票数据 ===
0 A
1 B
2 A
3 C
4 A
5 B
值 'A' 出现 6 次,占 50%
值 'B' 出现 4 次,约 33.3%
值 'C' 出现 2 次,约 16.7%
=== 相对比例 ===
A 0.500000
B 0.333333
C 0.166667
dtype: float64
=== 升序排列 ===
C 2
B 4
A 6
dtype: int64
Code analysis:
- Use
normalize=TrueYou can quickly compute the share of each category. - All proportions add up to 1.0, which makes share analysis convenient.
- Use
ascending=TrueYou can view the result in ascending order of frequency.
Example 3: Working with numeric data and using the bins parameter
For continuous numeric values, you can use the bins parameter to bin the data and count frequencies.
Example
import
pandas
as
pd
import
numpy
as
np
1. Create numeric data
scores
=
pd.
Series
(
[
85
,
90
,
78
,
92
,
88
,
76
,
95
,
82
,
70
,
89
,
91
,
77
,
84
,
86
]
)
(
"=== Student scores ==="
)
(
scores
)
2. No binning - count each unique value
(
"\n=== Count each score ==="
)
(
pd.
value_counts
(
scores
)
)
3. Bin using the bins parameter
(
"\n=== Split into 4 bins ==="
)
result_bins
=
pd.
value_counts
(
scores
,
bins
=
4
)
(
result_bins
)
4. View the bin edges
(
"\n=== Bin edges ==="
)
(
f
"Minimum: {scores.min()}, maximum: {scores.max()}"
)
Expected output:
=== 学生成绩 ===
[85, 90, 78, 92, 88, 76, 95, 82, 70, 89, 91, 77, 84, 86]
=== 统计每个分数 ===
85 2
90 1
78 1
92 1
88 1
76 1
95 1
82 1
70 1
89 1
91 1
77 1
84 1
86 1
Name: count, dtype: int64
=== 分成 4 个箱 ===
result_bins = pd.value_counts(scores, bins=4)
(88.75, 95.0] 5
(82.5, 88.75] 4
(76.25, 82.5] 3
(69.97399999999999, 76.25] 2
Name: count, dtype: int64
=== 分箱边界 ===
最小值: 70, 最大值: 95
This is similar to a histogram and shows that the scores are mainly concentrated in the mid-to-high range. The bins parameter divides numeric data into discrete bins by range and then counts how many values fall into each bin.
Example 4: Handling missing values
Use dropna parameter lets you control whether missing values are counted.
Example
import
pandas
as
pd
import
numpy
as
np
1. Data containing missing values
data
=
pd.
Series
(
[
'a'
,
'b'
,
np.
nan
,
'a'
,
None
,
'c'
,
np.
nan
,
'b'
,
'a'
]
)
(
"=== Data containing missing values ==="
)
(
data
)
2. Exclude NaN by default (dropna=True)
(
"\n=== Exclude NaN by default ==="
)
(
pd.
value_counts
(
data
)
)
3. Include NaN (dropna=False)
(
"\n=== Include NaN ==="
)
(
pd.
value_counts
(
data
,
dropna
=
False
)
)
4. Count missing numeric values
numeric_data
=
pd.
Series
(
[
1
,
2
,
np.
nan
,
3
,
2
,
np.
nan
,
1
,
4
]
)
(
"\n=== Numeric data including NaN ==="
)
(
pd.
value_counts
(
numeric_data
,
dropna
=
False
)
)
Expected output:
=== 包含缺失值的数据 ===
0 a
1 b
2 NaN
3 a
4 None
5 c
6 NaN
7 b
8 a
dtype: object
=== 默认不包含 NaN ===
a 3
b 2
c 1
dtype: 64
=== 包含 NaN (dropna=False) ===
a 3
b 2
NaN 2 # 2 个 NaN (2 个 np.nan)
c 1
dtype: int64
=== 数值型数据包含 NaN ===
1.0 2
2.0 2
NaN 2 # 2 个 NaN
3.0 1
4.0 1
dtype: int64
Code analysis:
- By default (
dropna=True), NaN values are not counted. - Use
dropna=FalseYou can see the number of missing values, which is useful in data quality analysis. - The same applies to numeric data.
Tip:
pd.value_counts()It is one of the most important functions in exploratory data analysis and gives you a quick understanding of the data distribution. If you only need a list of unique values without their frequencies, usepd.unique()function in Vue 3.
Common Pandas functions