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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。