你可以使用**value_counts()**函数来计算pandas系列中唯一数值的频率。
这个函数使用以下基本语法。
my_series.value_counts()
下面的例子展示了如何在实践中使用这种语法。
例1:计算唯一值的频率
下面的代码显示了如何计算一个pandas系列中唯一值的出现次数。
import pandas as pd
#create pandas Series
my_series = pd.Series([3, 3, 3, 3, 4, 4, 7, 7, 8, 9])
#count occurrences of unique values in Series
my_series.value_counts()
3 4
4 2
7 2
8 1
9 1
dtype: int64
这告诉我们。
- 值3出现了4次。
- 值4出现了2次。
- 值7出现了2次。
以此类推。
例2:计算唯一值(包括NaN)的频率
默认情况下,**value_counts()**函数并不显示NaN值的频率。
但是,你可以使用dropna参数来显示 NaN 值的频率。
import pandas as pd
import numpy as np
#create pandas Series with some NaN values
my_series = pd.Series([3, 3, 3, 3, 4, 4, 7, 7, 8, 9, np.nan, np.nan])
#count occurrences of unique values in Series, including NaNs
my_series.value_counts(dropna=False)
3.0 4
4.0 2
7.0 2
NaN 2
8.0 1
9.0 1
dtype: int64
例3:计算唯一值的相对频率
下面的代码显示了如何使用normalize参数来计算pandas系列中唯一值的相对频率。
import pandas as pd
#create pandas Series
my_series = pd.Series([3, 3, 3, 3, 4, 4, 7, 7, 8, 9])
#count occurrences of unique values in Series
my_series.value_counts(normalize=True)
3 0.4
4 0.2
7 0.2
8 0.1
9 0.1
dtype: float64
这告诉我们。
- 值3占系列中所有值的40%。
- 值4代表了系列中所有值的20%。
- 值7代表了系列中所有值的20%。
以此类推。
例子4:在Bins中计算频率
下面的代码显示了如何使用bins参数来计算 pandas 系列中落入同等大小的bin中的数值的频率。
import pandas as pd
#create pandas Series
my_series = pd.Series([3, 3, 3, 3, 4, 4, 7, 7, 8, 9])
#count occurrences of unique values in Series
my_series.value_counts(bins=3)
(3.0, 5.0] 6
(5.0, 7.0] 2
(7.0, 9.0] 2
dtype: int64
这告诉我们。
- 有6个值落在3到5的范围内。
- 有2个值落在5到7的范围内。
- 有2个值在7到9的范围内。
例5:计算潘达斯数据框架中数值的频率
我们也可以使用**value_counts()**函数来计算pandas DataFrame中某一列的唯一值的频率。
import pandas as pd
#create DataFrame
df = pd.DataFrame({'points': [9, 9, 9, 10, 10, 13, 15, 22],
'assists': [5, 7, 7, 9, 12, 9, 9, 4],
'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})
#count occurrences of unique values in 'points' column
df['points'].value_counts()
9 3
10 2
13 1
15 1
22 1
Name: points, dtype: int64
其他资源
下面的教程介绍了如何使用pandas中的其他常用函数。
如何在Pandas中使用describe()函数
如何在Pandas中计算行的数量
如何在Pandas中按组计算观察数据
The postHow to Use Pandas value_counts() Function (With Examples) appeared first onStatology.