numpy.bincount#
- numpy.bincount(x, /, weights=None, minlength=0)#
計算非負整數陣列中每個值出現的次數。
bin (大小為 1) 的數量比 x 中的最大值大 1。如果指定了 minlength,則輸出陣列中將至少有這麼多 bin(但如有必要,它會更長,具體取決於 x 的內容)。每個 bin 給出其索引值在 x 中出現的次數。如果指定了 weights,則輸入陣列會由此加權,即如果在位置
i
找到值n
,則out[n] += weight[i]
而不是out[n] += 1
。- 參數:
- xarray_like, 1 維度, 非負整數
輸入陣列。
- weightsarray_like, 選用
權重,與 x 相同形狀的陣列。
- minlengthint, 選用
輸出陣列的最小 bin 數量。
- 傳回值:
- outndarray of ints
對輸入陣列進行 binning 的結果。out 的長度等於
np.amax(x)+1
。
- 引發:
- ValueError
如果輸入不是 1 維,或包含負值元素,或者如果 minlength 為負數。
- TypeError
如果輸入的類型為浮點數或複數。
範例
>>> import numpy as np >>> np.bincount(np.arange(5)) array([1, 1, 1, 1, 1]) >>> np.bincount(np.array([0, 1, 1, 3, 2, 1, 7])) array([1, 3, 1, 1, 0, 0, 0, 1])
>>> x = np.array([0, 1, 1, 3, 2, 1, 7, 23]) >>> np.bincount(x).size == np.amax(x)+1 True
輸入陣列需要為整數 dtype,否則會引發 TypeError
>>> np.bincount(np.arange(5, dtype=float)) Traceback (most recent call last): ... TypeError: Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe'
bincount
的一種可能用途是使用weights
關鍵字對陣列的可變大小區塊執行總和。>>> w = np.array([0.3, 0.5, 0.2, 0.7, 1., -0.6]) # weights >>> x = np.array([0, 1, 1, 2, 2, 2]) >>> np.bincount(x, weights=w) array([ 0.3, 0.7, 1.1])