Python 的 numpy 模塊提供了一個名為 numpy.histogram() 的函數。此函數表示與一組值範圍進行比較的值數量的頻率。這個函數類似於matplotlib.pyplot的hist()函數。
簡單來說,這個函數用於計算數據集的直方圖。
用法:
numpy.histogram(x, bins=10, range=None, normed=None, weights=None, density=None)
參數:
x:數組
此參數定義了一個扁平化的數組,在該數組上計算直方圖。
bins:int 或 str 或標量序列(可選)
如果此參數定義為整數,則在給定範圍內,它定義了 equal-width 個 bin 的數量。否則,定義單調增加的 bin 邊數組。它還包括最右邊的邊,允許不均勻的 bin 寬度。最新版本的 numpy 允許我們將 bin 參數設置為字符串,它定義了一種計算最佳 bin 寬度的方法。
範圍:(浮點數,浮點數)(可選)
該參數定義了 bin 的 lower-upper 範圍。默認情況下,範圍是 (x.min(), x.max())。超出範圍的值將被忽略。第一個元素的範圍應該等於或小於第二個元素。
規範:布爾(可選)
此參數與密度參數相同,但它可能會為不相等的 bin 寬度提供錯誤的輸出。
權重:數組(可選)
該參數定義了一個包含權重且形狀與 'x' 相同的數組。
密度:布爾(可選)
如果設置為 True,將導致每個 bin 中的樣本數。如果其值為 False,則密度函數將導致 bin 中概率密度函數的值。
返回值:
曆史:數組
密度函數返回直方圖的值。
edge_bin:浮點型數組
此函數返回 bin 邊 (length(hist+1))。
範例1:
import numpy as np
a=np.histogram([1, 5, 2], bins=[0, 1, 2, 3])
a
輸出:
(array([0, 1, 1], dtype=int64), array([0, 1, 2, 3]))
在上麵的代碼中
- 我們已經導入了別名為 np.
- 我們已經聲明了變量 'a' 並分配了 np.histogram() 函數的返回值。
- 我們在函數中傳遞了一個數組和 bin 的值。
- 最後,我們嘗試打印 'a' 的值。
在輸出中,它顯示了一個包含直方圖值的 ndarray。
範例2:
import numpy as np
x=np.histogram(np.arange(6), bins=np.arange(7), density=True)
x
輸出:
(array([0.16666667, 0.16666667, 0.16666667, 0.16666667, 0.16666667, 0.16666667]), array([0, 1, 2, 3, 4, 5, 6]))
範例3:
import numpy as np
x=np.histogram([[1, 3, 1], [1, 3, 1]], bins=[0,1,2,3])
x
輸出:
(array([0, 4, 2], dtype=int64), array([0, 1, 2, 3]))
範例4:
import numpy as np
a = np.arange(8)
hist, bin_edges = np.histogram(a, density=True)
hist
bin_edges
輸出:
array([0.17857143, 0.17857143, 0.17857143, 0. , 0.17857143, 0.17857143, 0. , 0.17857143, 0.17857143, 0.17857143]) array([0. , 0.7, 1.4, 2.1, 2.8, 3.5, 4.2, 4.9, 5.6, 6.3, 7. ])
範例5:
import numpy as np
a = np.arange(8)
hist, bin_edges = np.histogram(a, density=True)
hist
hist.sum()
np.sum(hist * np.diff(bin_edges))
輸出:
array([0.17857143, 0.17857143, 0.17857143, 0. , 0.17857143, 0.17857143, 0. , 0.17857143, 0.17857143, 0.17857143]) 1.4285714285714288 1.0
在上麵的代碼中
- 我們已經導入了別名為 np.
- 我們使用 np.arange() 函數創建了一個數組 'a'。
- 我們已經聲明了變量 'hist' 和 'bin_edges',然後分配了 np.histogram() 函數的返回值。
- 我們已經傳遞了數組 'a' 並在函數中將 'density' 設置為 True。
- 我們嘗試打印 'hist' 的值。
- 最後,我們嘗試使用 hist.sum() 和 np.sum() 計算直方圖值的總和,其中我們傳遞了直方圖值和 bin 的邊。
在輸出中,它顯示了一個包含直方圖值和直方圖值總和的 ndarray。
相關用法
- Python numpy.hypot()用法及代碼示例
- Python numpy.hsplit()用法及代碼示例
- Python numpy.hstack()用法及代碼示例
- Python numpy.less()用法及代碼示例
- Python numpy.tril()用法及代碼示例
- Python numpy.fromstring()用法及代碼示例
- Python numpy.random.standard_normal()用法及代碼示例
- Python numpy.lookfor()用法及代碼示例
- Python numpy.nonzero()用法及代碼示例
- Python numpy.maximum_sctype()用法及代碼示例
- Python numpy.ma.make_mask_none()用法及代碼示例
- Python numpy.mean()用法及代碼示例
- Python numpy.nancumsum()用法及代碼示例
- Python numpy.atleast_2d()用法及代碼示例
- Python numpy.isreal()用法及代碼示例
- Python numpy.place()用法及代碼示例
- Python numpy.invert()用法及代碼示例
- Python numpy.polymul()用法及代碼示例
- Python numpy.partition()用法及代碼示例
- Python numpy.angle()用法及代碼示例
注:本文由純淨天空篩選整理自 numpy.histogram() in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。