Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas pd.value_counts() function

Pandas pd.value_counts() function

Pandas Universal Functions Common Pandas functions


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

- Type: Series or array-like object. - Description: The data whose frequencies you want to count. Usually a Series. - Type> boolean. - Type: bool. - Type: bool. - Type: int or None. - Type: bool.

Function description


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'

]

)

print

(

"=== Original Series ==="

)

print

(

colors

)

2. Use pd.value_counts() to count frequencies

result

=

pd.

value_counts

(

colors

)

print

(

"\n=== pd.value_counts() frequency count ==="

)

print

(

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:

  1. 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.
  2. 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'

]

)

print

(

"=== Voting data ==="

)

print

(

votes

)

1. Absolute frequencies

print

(

"\n=== Absolute frequencies ==="

)

print

(

pd.

value_counts

(

votes

)

)

2. Relative proportions (normalize=True)

print

(

"\n=== Relative proportions ==="

)

result_normalized

=

pd.

value_counts

(

votes

,

normalize

=

True

)

print

(

result_normalized

)

print

(

f

"\nSum of proportions: {result_normalized.sum():.2f}"

)

3. Sort in ascending order

print

(

"\n=== Ascending order ==="

)

print

(

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:

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

]

)

print

(

"=== Student scores ==="

)

print

(

scores

)

2. No binning - count each unique value

print

(

"\n=== Count each score ==="

)

print

(

pd.

value_counts

(

scores

)

)

3. Bin using the bins parameter

print

(

"\n=== Split into 4 bins ==="

)

result_bins

=

pd.

value_counts

(

scores

,

bins

=

4

)

print

(

result_bins

)

4. View the bin edges

print

(

"\n=== Bin edges ==="

)

print

(

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'

]

)

print

(

"=== Data containing missing values ==="

)

print

(

data

)

2. Exclude NaN by default (dropna=True)

print

(

"\n=== Exclude NaN by default ==="

)

print

(

pd.

value_counts

(

data

)

)

3. Include NaN (dropna=False)

print

(

"\n=== Include NaN ==="

)

print

(

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

]

)

print

(

"\n=== Numeric data including NaN ==="

)

print

(

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:


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, use pd.unique() function in Vue 3.

Pandas Common Functions Common Pandas functions