Pandas Series.value_counts(~) 方法返回系列中唯一值的计数。
参数
1.normalize | boolean | optional
是否对计数进行归一化,使其总和为 1。默认情况下,normalize=False 。
2. sort | boolean | optional
是否按计数排序。默认情况下,sort=True 。
3. ascending | boolean | optional
此参数仅在 sort=True 时相关。
-
如果是
True,则按升序排序 -
如果是
False,则按降序排序
默认情况下,ascending=False 。
4. bins | int | optional
如果设置了 bins,则计数将基于间隔。间隔的宽度将如下确定:
[max(Series) - min(Series)] / bins
默认情况下,bins=None 。
5. dropna | boolean | optional
-
如果
True,则NaN将被忽略。 -
如果
False,则NaN也将被计数。
默认情况下, dropna=True ,
返回值
一个Series。
例子
基本用法
要获取系列中唯一值的计数:
s = pd.Series([4,3,3,5,np.nan])
s.value_counts()
3.0 2
5.0 1
4.0 1
dtype: int64
在这里,请注意默认情况下如何忽略 dropna=True 以来的缺失值。
指定标准化
将计数归一化,使其总和为 1:
s = pd.Series([4,3,3,5,np.nan])
s.value_counts(normalize=True)
3.0 0.50
5.0 0.25
4.0 0.25
dtype: float64
指定排序
默认情况下, sort=True ,这意味着结果系列按计数排序:
s = pd.Series([4,3,3,5,np.nan])
s.value_counts()
3.0 2
5.0 1
4.0 1
dtype: int64
设置 sort=False 将禁用此类排序:
s = pd.Series([4,3,3,5,np.nan])
s.value_counts(sort=False)
4.0 1
3.0 2
5.0 1
dtype: int64
指定升序
默认情况下, ascending=True ,这意味着结果系列按计数升序排序:
s = pd.Series([4,3,3,5,np.nan])
s.value_counts()
4.0 1
5.0 1
3.0 2
dtype: int64
要按降序排序,请像这样设置ascending=False:
s = pd.Series([4,3,3,5,np.nan])
s.value_counts(ascending=False)
3.0 2
5.0 1
4.0 1
dtype: int64
指定箱子
我们可以通过传递bins来基于间隔进行计数,而不是计算唯一值,如下所示:
s = pd.Series([4,3,3,5,np.nan])
s.value_counts(bins=3)
(2.9970000000000003, 3.667] 2
(4.333, 5.0] 1
(3.667, 4.333] 1
dtype: int64
这里,2 个值位于区间 2.997 和 3.667 中。
请注意,每个间隔的宽度由以下公式计算:
[max(s) - min(s)] / 3 = 2/3 = 0.666
计算 value_counts 中的 nan
默认情况下, dropna=True ,这意味着所有 NaN 都会被忽略。我们可以选择通过传入 dropna=False 将它们包含在计数中,如下所示:
s = pd.Series([4,3,3,5,np.nan])
s.value_counts(dropna=False)
3.0 2
NaN 1
5.0 1
4.0 1
dtype: int64
相关用法
- Python Pandas Series str extractall方法用法及代码示例
- Python Pandas Series str split方法用法及代码示例
- Python Pandas Series to_list方法用法及代码示例
- Python Pandas Series str center方法用法及代码示例
- Python Pandas Series between方法用法及代码示例
- Python Pandas Series str pad方法用法及代码示例
- Python Pandas Series map方法用法及代码示例
- Python Pandas Series hasnans属性用法及代码示例
- Python Pandas Series is_monotonic属性用法及代码示例
- Python Pandas Series str extract方法用法及代码示例
- Python Pandas Series string contains方法用法及代码示例
- Python Pandas Series to_frame方法用法及代码示例
- Python Pandas Series zfill方法用法及代码示例
- Python Pandas Series argmax方法用法及代码示例
- Python Pandas Series str replace方法用法及代码示例
- Python Pandas Series str len方法用法及代码示例
- Python Pandas Series str lower方法用法及代码示例
- Python Pandas Series is_monotonic_increasing属性用法及代码示例
- Python Pandas Series str strip方法用法及代码示例
- Python Pandas Series is_unique属性用法及代码示例
- Python Pandas Series str rstrip方法用法及代码示例
- Python Pandas Series str lstrip方法用法及代码示例
- Python Pandas Series argmin方法用法及代码示例
- Python Pandas Series is_monotonic_decreasing属性用法及代码示例
- Python Pandas Series.cumsum()用法及代码示例
注:本文由纯净天空筛选整理自Isshin Inada大神的英文原创作品 Pandas Series | value_counts method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
