在 Python 中無需庫查詢平均值、中位數和眾數


平均值、中位數和眾數在資料分析中是非常常用的統計函式。儘管有一些 Python 庫。

查詢平均值

數字列表的平均值也稱為數字的平均值。它是透過將所有數字的總和除以數字的個數來找到的。在下面的示例中,我們應用 sum() 函式來獲取數字的總和,並應用 len() 函式來獲取數字的個數。

示例

num_list = [21, 11, 19, 3,11,5]
# FInd sum of the numbers
num_sum = sum(num_list)
#divide the sum with length of the list
mean = num_sum / len(num_list)
print(num_list)
print("Mean of the above list of numbers is: " + str(round(mean,2)))

輸出

執行以上程式碼得到以下結果:

[21, 11, 19, 3, 11, 5]
Mean of the above list of numbers is: 11.67

查詢中位數

中位數是數字列表中最中間的值。如果列表中數字的個數是奇數,那麼我們對列表進行排序並選擇最中間的值。如果個數是偶數,那麼我們選擇兩個最中間的值並取它們的平均值作為中位數。

示例

num_list = [21, 13, 19, 3,11,5]
# Sort the list
num_list.sort()
# Finding the position of the median
if len(num_list) % 2 == 0:
   first_median = num_list[len(num_list) // 2]
   second_median = num_list[len(num_list) // 2 - 1]
   median = (first_median + second_median) / 2
else:
   median = num_list[len(num_list) // 2]
print(num_list)
print("Median of above list is: " + str(median))

輸出

執行以上程式碼得到以下結果:

[3, 5, 11, 13, 19, 21]
Median of above list is: 12.0

查詢眾數

眾數是列表中出現頻率最高的數字。我們透過查詢列表中每個數字的頻率,然後選擇頻率最高的數字來計算它。

示例

import collections
# list of elements to calculate mode
num_list = [21, 13, 19, 13,19,13]

# Print the list
print(num_list)

# calculate the frequency of each item
data = collections.Counter(num_list)
data_list = dict(data)

# Print the items with frequency
print(data_list)

# Find the highest frequency
max_value = max(list(data.values()))
mode_val = [num for num, freq in data_list.items() if freq == max_value]
if len(mode_val) == len(num_list):
   print("No mode in the list")
else:
   print("The Mode of the list is : " + ', '.join(map(str, mode_val)))

輸出

執行以上程式碼得到以下結果:

[21, 13, 19, 13, 19, 13]
{21: 1, 13: 3, 19: 2}
The Mode of the list is : 13

更新於:2019年8月7日

10K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告