Python学习笔记:counts、value_counts统计次数

一、介绍

Python 中利用 pd.value_counts() 函数对数据频次进行统计。

该函数返回一个序列 Series ,包含每个值的数量。

  • 使用语法为:
Series.value_counts(normalize=False,  # 是否显示占比
                    sort=True,   # 是否排序
                    ascending=False,  # 默认降序
                    bins=None,  # 分区
                    dropna=True) # 是否删除空缺值

二、实操

1.默认统计

import pandas as pd
import numpy as np

# 默认:忽略空值 按次数排序
s = pd.Series([1,3,2,2,3,4,np.nan])
s.value_counts()
'''
3.0    2
2.0    2
4.0    1
1.0    1
dtype: int64
'''

2.计数占比

# 计数占比
s.value_counts(normalize=True)
'''
3.0    0.333333
2.0    0.333333
4.0    0.166667
1.0    0.166667
dtype: float64
'''

3.自定义分组区间

区间化(Binning)。

# 自定义分组区间
s.value_counts(bins=3)
'''
(0.996, 2.0]    3
(2.0, 3.0]      2
(3.0, 4.0]      1
dtype: int64
'''

4.空值处理

# 不删除空值
s.value_counts(dropna=False)
'''
3.0    2
2.0    2
NaN    1
4.0    1
1.0    1
dtype: int64
'''

5.升序

s.value_counts(ascending=True)
'''
4.0    1
1.0    1
3.0    2
2.0    2
dtype: int64
'''

三、counts函数

1.使用语法

count(str, start=0, end=len(string))

2.具体案例

df_str = 'asdfaflzfasdfnasdf我是你的你是我的'
df_str.count('a') # 4
df_str.count('3') # 0
df_str.count('你') # 2

df_list = [1,2,3,4,5,4,4,4,2,'a','b','a','子','子']
df_list.count(4) # 4
df_list.count('4') # 0
df_list.count(a) # NameError: name 'a' is not defined
df_list.count('a') # 2

参考链接:pandas.Series.value_counts

参考链接:pandas计数函数 :value_counts( )和counts( )的使用

参考链接:Pandas | 5 种技巧高效利用value-counts

原文地址:https://www.cnblogs.com/hider/p/15763390.html