Numpy 的 where(~)
方法將布爾數組映射到指定的輸出,類似於 if-else
的工作方式。
參數
1.condition
| array_like
共 booleans
布爾值數組。
2. x
| array_like
True 的所有實例都將替換為 x。
3. y
| array_like
所有 False 實例都將被 y 替換。
返回值
一個 Numpy 數組。
例子
基本測繪
要將所有 True
替換為 5,將所有 False
替換為 10:
x = np.array([True, True, False, False])
np.where(x, 5, 10)
array([5, 5, 10, 10])
使用布爾掩碼
更實際的是,where()
方法與布爾掩碼配合使用效果很好。假設我們希望所有大於 2 的值均為 10,所有其他值均為 -1。
我們首先構建一個布爾掩碼,如下所示:
x = np.array([1,2,3,4])
mask = x > 2
mask
array([False, False, True, True])
然後我們應用映射:
np.where(mask, 10, -1)
array([-1, -1, 10, 10])
根據數字替換值
假設我們想根據特定標準執行一些算術。例如,我們要對大於 2 的值加 5,否則減 5:
x = np.array([1,2,3,4])
np.where(x>2, x+5, x-5)
array([-4, -3, 8, 9])
多維數組
方法where(~)
也可用於多維數組:
x = np.array([[1,2],[3,4]])
np.where(x>2, 10, 5)
array([[5, 5],
[10, 10]])
相關用法
- Python Tableau workbooks.populate_preview_image用法及代碼示例
- Python wsgiref.simple_server.make_server用法及代碼示例
- Python wsgiref.util.FileWrapper用法及代碼示例
- Python Tableau workbooks.get_by_id用法及代碼示例
- Python Tableau workbooks.update用法及代碼示例
- Python Tableau workbooks.update_connection用法及代碼示例
- Python wsgiref.util.setup_testing_defaults用法及代碼示例
- Python Tableau workbooks.download用法及代碼示例
- Python Tableau workbooks.populate_views用法及代碼示例
- Python OpenCV waitKeyEx()用法及代碼示例
- Python winsound.SND_ALIAS用法及代碼示例
- Python Tableau workbooks.get用法及代碼示例
- Python weakref.WeakMethod用法及代碼示例
- Python Tableau workbooks.publish用法及代碼示例
- Python wsgiref.validate.validator用法及代碼示例
- Python BeautifulSoup wrap方法用法及代碼示例
- Python OpenCV waitKey()用法及代碼示例
- Python Tableau workbooks.delete用法及代碼示例
- Python Tableau workbooks.refresh用法及代碼示例
- Python Tableau workbooks.populate_connections用法及代碼示例
- Python Tableau workbooks.populate_pdf用法及代碼示例
- Python cudf.core.column.string.StringMethods.is_vowel用法及代碼示例
- Python NumPy fliplr方法用法及代碼示例
- Python torch.distributed.rpc.rpc_async用法及代碼示例
- Python torch.nn.InstanceNorm3d用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 NumPy | where method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。