當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Pandas Index.value_counts()用法及代碼示例

Python是進行數據分析的一種出色語言,主要是因為以數據為中心的python軟件包具有奇妙的生態係統。 Pandas是其中的一種,使導入和分析數據更加容易。

Pandas Index.value_counts()函數返回包含唯一值計數的對象。結果對象將按降序排列,因此第一個元素是最frequently-occurring元素。默認情況下不包括NA值。

用法: Index.value_counts(normalize=False, sort=True, ascending=False, bins=None, dropna=True)

參數:
normalize:如果為True,則返回的對象將包含唯一值的相對頻率。
sort:按值排序
ascending:升序排列
bins:而不是對值進行計數,而是將它們分組到half-open箱中,這是pd.cut的一種便利,僅適用於數字數據
dropna:不包括NaN計數。

返回:數量:係列

範例1:采用Index.value_counts()函數計算給定索引中唯一值的數量。

# importing pandas as pd 
import pandas as pd 
  
# Creating the index 
idx = pd.Index(['Harry', 'Mike', 'Arther', 'Nick', 
                'Harry', 'Arther'], name ='Student') 
  
# Print the Index 
print(idx)

輸出:

讓我們找到索引中所有唯一值的計數。

# find the count of unique values in the index 
idx.value_counts()

輸出:

該函數已返回給定索引中所有唯一值的計數。請注意,函數返回的對象包含值的降序出現。

範例2:采用Index.value_counts()函數查找給定索引中所有唯一值的計數。

# importing pandas as pd 
import pandas as pd 
  
# Creating the index 
idx = pd.Index([21, 10, 30, 40, 50, 10, 50]) 
  
# Print the Index 
print(idx)

輸出:

讓我們計算一下索引中所有唯一值的出現。

# for finding the count of all  
# unique values in the index. 
idx.value_counts()

輸出:

該函數已返回索引中所有唯一值的計數。



相關用法


注:本文由純淨天空篩選整理自Shubham__Ranjan大神的英文原創作品 Python | Pandas Index.value_counts()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。