NumPy 的 histogram(~)
方法計算直方圖(frequency-count 圖)。
參數
1. a
| array-like
輸入數組。
2. bins
| array-like
| optional
所需的箱子數量。如果提供了數組,則它必須包含邊。默認情況下,我們得到 10 個equal-width bin。
3. range
| float
的tuple
| optional
默認情況下,範圍設置為(a.min()
、a.max()
)。
4. weights
| array-like
| optional
包含每個輸入值的權重的數組。如果某個值落在特定的 bin 中,我們不會將計數增加 1,而是增加相應的權重。形狀必須與 a
相同。默認情況下,權重均為一。
5. density
| boolean
| optional
是否歸一化為概率密度函數(即總麵積等於 1)。默認情況下,density=False
。
返回值
兩個 NumPy 數組的元組:
-
直方圖的值(即頻率計數)
-
箱子邊
例子
基本用法
my_hist, bin_edges = np.histogram([1,3,6,6,10])
print("hist:", my_hist)
print("bin_edges:", bin_edges)
hist: [1 0 1 0 0 2 0 0 0 1]
bin_edges: [ 1. 1.9 2.8 3.7 4.6 5.5 6.4 7.3 8.2 9.1 10. ]
這裏,bin_edges
表示bin的間隔,hist
表示落在該間隔之間的值的數量。例如,總共有一項位於 1
和 1.9
之間,因此我們得到直方圖中該點的值 1
。
指定 bin 的數量
my_hist, bin_edges = np.histogram([1,3,6,6,10], bins=5)
print("hist:", my_hist)
print("bin_edges:", bin_edges)
hist: [1 1 2 0 1]
bin_edges: [ 1. 2.8 4.6 6.4 8.2 10. ]
指定 bin 邊
my_hist, bin_edges = np.histogram([1,3,6,6,10], bins=[1,5,10])
print("hist:", my_hist)
print("bin_edges:", bin_edges)
hist: [2 3]
bin_edges: [ 1 5 10]
指定範圍
my_hist, bin_edges = np.histogram([1,3,6,6,10], range=(0,20))
print("hist:", my_hist)
print("bin_edges:", bin_edges)
hist: [1 1 0 2 0 1 0 0 0 0]
bin_edges: [ 0. 2. 4. 6. 8. 10. 12. 14. 16. 18. 20.]
指定權重
my_hist, bin_edges = np.histogram([1,3,6,6,10], weights=[1,5,1,1,1])
print("hist:", my_hist)
print("bin_edges:", bin_edges)
hist: [1 0 5 0 0 2 0 0 0 1]
bin_edges: [ 1. 1.9 2.8 3.7 4.6 5.5 6.4 7.3 8.2 9.1 10. ]
我們得到 5 的原因是輸入數組中的兩個 6 顯然屬於同一個 bin,並且由於它們各自的權重是 4 和 5,所以我們最終得到的總 bin 計數為 4+5=9
。
標準化
my_hist, bin_edges = np.histogram([1,3,6,6,10], density=True)
print("hist:", my_hist)
print("bin_edges:", bin_edges)
hist: [0.22222222 0. 0.22222222 0. 0. 0.44444444 0. 0. 0. 0.22222222]
bin_edges: [ 1. 1.9 2.8 3.7 4.6 5.5 6.4 7.3 8.2 9.1 10. ]
相關用法
- Python hashlib.sha3_256()用法及代碼示例
- Python help()用法及代碼示例
- Python NumPy hstack方法用法及代碼示例
- Python BeautifulSoup has_attr方法用法及代碼示例
- Python hasattr方法用法及代碼示例
- Python http.HTTPStatus用法及代碼示例
- Python hashlib.sha3_512()用法及代碼示例
- Python help方法用法及代碼示例
- Python hashlib.shake_256()用法及代碼示例
- Python hashlib.shake_128()用法及代碼示例
- Python NumPy hypot方法用法及代碼示例
- Python hashlib.blake2s()用法及代碼示例
- Python hashlib.blake2b()用法及代碼示例
- Python hasattr()用法及代碼示例
- Python html.escape()用法及代碼示例
- Python statistics harmonic_mean()用法及代碼示例
- Python html.unescape()用法及代碼示例
- Python math hypot()用法及代碼示例
- Python hash()用法及代碼示例
- Python hashlib.sha3_224()用法及代碼示例
- Python hex方法用法及代碼示例
- Python hex()用法及代碼示例
- Python OpenCV haveImageReader()用法及代碼示例
- Python NumPy hsplit方法用法及代碼示例
- Python http.client.HTTPConnection.set_tunnel用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 NumPy | histogram method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。