本文簡要介紹 python 語言中 numpy.digitize
的用法。
用法:
numpy.digitize(x, bins, right=False)
返回輸入數組中每個值所屬的 bin 的索引。
正確的
箱子的順序
返回的索引 i 滿足
False
increasing
bins[i-1] <= x < bins[i]
True
increasing
bins[i-1] < x <= bins[i]
False
decreasing
bins[i-1] > x >= bins[i]
True
decreasing
bins[i-1] >= x > bins[i]
如果值在x超出了範圍箱子, 0 或
len(bins)
酌情返回。- x: array_like
要分箱的輸入數組。在NumPy 1.10.0 之前,此數組必須是一維的,但現在可以具有任何形狀。
- bins: array_like
箱陣列。它必須是一維且單調的。
- right: 布爾型,可選
指示間隔是否包括右側或左側 bin 邊。默認行為是 (right==False),表示區間不包括右邊。在這種情況下,左 bin 端是打開的,即 bins[i-1] <= x < bins[i] 是單調遞增 bins 的默認行為。
- indices: 整數數組
索引的輸出數組,形狀與x.
- ValueError
如果 bins 不是單調的。
- TypeError
如果輸入的類型很複雜。
參數:
返回:
拋出:
注意:
如果值在x是這樣的,它們落在 bin 範圍之外,試圖索引箱子與 index
digitize
返回將導致 IndexError。np.digitize 是根據 np.searchsorted 實現的。這意味著使用二分搜索對值進行分箱,與之前的線性搜索相比,對於更多數量的箱來說,它的擴展性要好得多。它還消除了輸入數組為一維的要求。
對於單調_increasing_ bins,以下是等價的:
np.digitize(x, bins, right=True) np.searchsorted(bins, x, side='left')
請注意,由於參數的順序是顛倒的,所以邊也必須是顛倒的。
searchsorted
調用稍微快一些,因為它不進行任何單調性檢查。也許更重要的是,它支持所有 dtypes。例子:
>>> x = np.array([0.2, 6.4, 3.0, 1.6]) >>> bins = np.array([0.0, 1.0, 2.5, 4.0, 10.0]) >>> inds = np.digitize(x, bins) >>> inds array([1, 4, 3, 2]) >>> for n in range(x.size): ... print(bins[inds[n]-1], "<=", x[n], "<", bins[inds[n]]) ... 0.0 <= 0.2 < 1.0 4.0 <= 6.4 < 10.0 2.5 <= 3.0 < 4.0 1.0 <= 1.6 < 2.5
>>> x = np.array([1.2, 10.0, 12.4, 15.5, 20.]) >>> bins = np.array([0, 5, 10, 15, 20]) >>> np.digitize(x,bins,right=True) array([1, 2, 3, 4, 4]) >>> np.digitize(x,bins,right=False) array([1, 3, 3, 4, 5])
相關用法
- Python numpy diagonal用法及代碼示例
- Python numpy divmod用法及代碼示例
- Python numpy diagflat用法及代碼示例
- Python numpy divide用法及代碼示例
- Python numpy diag用法及代碼示例
- Python numpy diag_indices用法及代碼示例
- Python numpy disp用法及代碼示例
- Python numpy diff用法及代碼示例
- Python numpy dtype.isbuiltin用法及代碼示例
- Python numpy dtype.shape用法及代碼示例
- Python numpy dtype.ndim用法及代碼示例
- Python numpy dtype.alignment用法及代碼示例
- Python numpy dtype用法及代碼示例
- Python numpy dtype.names用法及代碼示例
- Python numpy dtype.__class_getitem__用法及代碼示例
- Python numpy dtype.flags用法及代碼示例
- Python numpy dtype.fields用法及代碼示例
- Python numpy dtype.subdtype用法及代碼示例
- Python numpy delete用法及代碼示例
- Python numpy dtype.descr用法及代碼示例
- Python numpy dec.setastest用法及代碼示例
- Python numpy datetime_as_string用法及代碼示例
- Python numpy dtype.kind用法及代碼示例
- Python numpy dtype.metadata用法及代碼示例
- Python numpy dsplit用法及代碼示例
注:本文由純淨天空篩選整理自numpy.org大神的英文原創作品 numpy.digitize。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。