where

paddle. where ( condition, x=None, y=None, name=None ) [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.

  • x (Tensor|scalar, 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, 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, optional) – For details, please refer to Name. Generally, no setting is required. Default: None.

Returns

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

Return type

Tensor

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]]),)