一、什麼是np.histogram函數
np.histogram函數是numpy庫中用於對數據進行統計分析的函數,可以輕鬆地計算出數據集的頻數分布情況。
該函數接受兩個參數,第一個參數是數據集,第二個參數是劃分數據的bins個數或邊緣值。函數返回一個二元組,其中第一個元素是頻數的列表,第二個元素是數據的範圍。
import numpy as np data = np.random.randn(1000) # 隨機生成1000個數據 hist, bins = np.histogram(data, bins=10) # 將數據劃分為10個bins,並計算頻數分布 print(hist) print(bins)
二、np.histogram函數的常用參數與用法
1、bins參數:用於設置數據的劃分方式,可以是整數,表示分段的個數,也可以是實數序列,表示分段的邊緣值。默認為10,通常建議根據數據的實際情況進行調整。
2、range參數:用於設置數據的範圍,計算出的頻數分布將會在該範圍內展示。同樣可以是整數或實數序列,不設置時以數據集的最小值和最大值為範圍。
3、density參數:用於確定頻數分布是否標準化,即是否除以總數使得和為1。默認為False。
4、cumulative參數:用於計算累積頻數分布,即小於等於該值的頻數之和。默認為False。
import numpy as np data = np.random.normal(0, 1, 1000) # 生成數據集 hist, bins = np.histogram(data, bins=20, range=(-5, 5), density=True, cumulative=True) # 將數據劃分為20個bins,並計算標準化的累積頻數分布 print(hist) print(bins)
三、np.histogram函數在數據可視化中的應用
np.histogram函數可以將數據集實現快速地轉化為頻數分布直方圖進行可視化展示,幫助研究人員更直觀地理解數據集的特徵。
例如,我們可以將數據集的頻數分布直方圖與正態分布的密度曲線進行比較,進一步探究數據的分布情況。
import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm data = np.random.normal(0, 1, 1000) hist, bins = np.histogram(data, bins=20, density=True) # 將數據劃分為20個bins,並計算標準化頻數分布 # 繪製頻數分布直方圖 plt.hist(data, bins=bins, density=True, alpha=0.5, color='blue') # 繪製正態分布曲線 mu, std = norm.fit(data) x = np.linspace(bins[0], bins[-1], 100) p = norm.pdf(x, mu, std) plt.plot(x, p, 'k', linewidth=2) plt.show()
四、np.histogram函數的其他應用場景
np.histogram函數不僅可以用於單個數據集的分析,還可以用於多個數據集之間的比較分析。
例如,我們可以通過np.histogram函數將多個數據集的頻數分布直方圖繪製在同一張圖中,以比較他們的分布情況。
import numpy as np import matplotlib.pyplot as plt data1 = np.random.normal(0, 1, 1000) data2 = np.random.normal(2, 1, 1000) data3 = np.random.normal(-2, 1, 1000) # 將多個數據集劃分為20個bins,並計算標準化頻數分布 hist1, bins1 = np.histogram(data1, bins=20, density=True) hist2, bins2 = np.histogram(data2, bins=20, density=True) hist3, bins3 = np.histogram(data3, bins=20, density=True) # 繪製頻數分布直方圖 plt.hist(data1, bins=bins1, density=True, alpha=0.5, color='blue') plt.hist(data2, bins=bins2, density=True, alpha=0.5, color='green') plt.hist(data3, bins=bins3, density=True, alpha=0.5, color='red') plt.show()
五、總結
通過np.histogram函數對數據集進行統計分析,可以更深入地了解數據集的特徵,並且在數據可視化中提供更準確的表現。
同時,np.histogram函數還可以進行多個數據集之間的比較分析,幫助研究人員更全面地掌握數據的分布情況。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/242138.html