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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM