Numpy 的 digitize(~)
方法返回一個 Numpy 數組,其中包含輸入數組中的值所屬的 bin 的索引。用簡單的語言來解釋是很困難的,所以請看例子來澄清。
參數
1. a
| array-like
值數組。
2. bins
| array-like
bin 數組,必須是一維並按升序排序。
3. right
| boolean
| optional
如果為 True,則值將被放置在端點的下一個 bin 中。如果為 False,則值將放置在前一個 bin 中。默認情況下,right=False
。
返回值
整數索引的 Numpy 數組。
例子
基本用法
考慮以下代碼片段:
# Our array of values
a = [3, 6.5, 9]
# Our bins
bins = [5, 6, 7, 8]
np.digitize(a, bins)
array([0, 2, 4])
讓我們理解這裏的輸出。
-
第一個值 3 介於 3 <= 5(第一個 bin)之間,因此返回的整數索引為 0。
-
第二個值 6.5 介於 6 和 7 之間(第 2 個和第 3 個 bin),因此返回的整數索引為 2。
-
第三個值 9 大於 8(第 4 個 bin),因此返回的整數索引為 4。
解決這個問題的一個好方法是考慮該值的索引(如果要將其插入到 bin 數組中)。例如,值 3 將被插入到索引 0 中,因此返回 0。 6.5 將插入到索引 2 中,因此返回 2,依此類推。
處理端點
默認情況下,當檢查將值放入哪個 bin 時,Numpy 將使用 < 比較。例如,
a = [5]
bins = [5, 6]
np.digitize(a, bins) # or right=False
array([1])
我們得到整數索引 1 的原因是我們執行的第一次比較是 5 < 5,其計算結果為 False
。
我們可以執行 <= 比較,而不是 < 比較,如下所示:
a = [5]
bins = [5, 6]
np.digitize(a, bins, right=True)
array([0])
在這裏,我們得到整數索引 0,因為第一個比較 5 <=5 的計算結果為 True
。
相關用法
- Python distributed.protocol.serialize.register_generic用法及代碼示例
- Python distributed.get_task_metadata用法及代碼示例
- Python distributed.Client.gather用法及代碼示例
- Python distributed.recreate_tasks.ReplayTaskClient.recreate_task_locally用法及代碼示例
- Python distributed.diagnostics.plugin.SchedulerPlugin用法及代碼示例
- Python distributed.Client.ncores用法及代碼示例
- Python distributed.Client.retire_workers用法及代碼示例
- Python distributed.Client.unregister_worker_plugin用法及代碼示例
- Python distributed.fire_and_forget用法及代碼示例
- Python dir用法及代碼示例
- Python distributed.Client.set_metadata用法及代碼示例
- Python dictionary cmp()用法及代碼示例
- Python distributed.Client.scheduler_info用法及代碼示例
- Python distributed.Client.submit用法及代碼示例
- Python distributed.Client.compute用法及代碼示例
- Python distributed.SpecCluster.scale用法及代碼示例
- Python distributed.get_worker用法及代碼示例
- Python distributed.SpecCluster.scale_up用法及代碼示例
- Python difflib.unified_diff用法及代碼示例
- Python distributed.Client.nthreads用法及代碼示例
- Python distributed.comm.resolve_address用法及代碼示例
- Python distributed.Client.unpublish_dataset用法及代碼示例
- Python distributed.get_task_stream用法及代碼示例
- Python distributed.Client.start_ipython_scheduler用法及代碼示例
- Python distributed.as_completed.batches用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 NumPy | digitize method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。