where

paddle. where ( condition: Tensor, x: Tensor | float | None = None, y: Tensor | float | None = None, name: str | None = None ) Tensor [source]

Return a Tensor of elements selected from either x or y according to corresponding elements of condition. Concretely,

\[\begin{split}out_i = \begin{cases} x_i, & \text{if} \ condition_i \ \text{is} \ True \\ y_i, & \text{if} \ condition_i \ \text{is} \ False \\ \end{cases}.\end{split}\]

Notes

numpy.where(condition) is identical to paddle.nonzero(condition, as_tuple=True), please refer to nonzero.

Parameters
  • condition (Tensor) – The condition to choose x or y. When True (nonzero), yield x, otherwise yield y, must have a dtype of bool if used as mask.

  • x (Tensor|scalar|None, optional) – A Tensor or scalar to choose when the condition is True with data type of bfloat16, float16, float32, float64, int32 or int64. Either both or neither of x and y should be given.

  • y (Tensor|scalar|None, optional) – A Tensor or scalar to choose when the condition is False with data type of bfloat16, float16, float32, float64, int32 or int64. Either both or neither of x and y should be given.

  • name (str|None, optional) – For details, please refer to Name. Generally, no setting is required. Default: None.

Returns

Tensor, A Tensor with the same shape as condition and same data type as x and y.

Examples

>>> import paddle

>>> x = paddle.to_tensor([0.9383, 0.1983, 3.2, 1.2])
>>> y = paddle.to_tensor([1.0, 1.0, 1.0, 1.0])

>>> out = paddle.where(x>1, x, y)
>>> print(out)
Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
[1.        , 1.        , 3.20000005, 1.20000005])

>>> out = paddle.where(x>1)
>>> print(out)
(Tensor(shape=[2, 1], dtype=int64, place=Place(cpu), stop_gradient=True,
[[2],
 [3]]),)