Elementwise masking
Replace invalid, masked, or disallowed tensor elements with a fallback value without writing an explicit Python loop.
PyTorch · Function
torch.where selects elements from input or other according to a condition, supporting broadcasting across the operands. With only a condition, it returns the indices of true elements.
torch.where performs elementwise selection: a true condition chooses input, while a false condition chooses other. The three operands are broadcast together, and the result has that broadcasted shape. With only condition, it instead returns the indices of true elements as a tuple.
torch.where(condition, input, other, *, out=None) → Tensor
torch.where(condition) → tuple of LongTensor| Name | Type | Description |
|---|---|---|
condition | BoolTensor | Boolean tensor; true or nonzero entries choose input, while false entries choose other. |
input | Tensor or Scalar | Tensor or scalar chosen where condition is true. |
other | Tensor or Scalar | Tensor or scalar chosen where condition is false. |
out | Tensor, optional | Optional destination tensor for the operation. |
For the three-argument form, a Tensor whose shape equals the broadcasted shape of condition, input, and other. The one-argument form returns a tuple of LongTensors.
import torch
condition = torch.tensor([True, False, True])
values = torch.tensor([1.0, 2.0, 3.0])
result = torch.where(condition, values, torch.tensor(0.0))
print(result) # tensor([1., 0., 3.])Selects each element from values when the corresponding condition is true; otherwise it selects zero.
Replace invalid, masked, or disallowed tensor elements with a fallback value without writing an explicit Python loop.
Choose between two tensors or between a tensor and a scalar while preserving a broadcasted tensor layout.
Obtain coordinates of entries satisfying a Boolean mask using the one-argument overload.
torch.where(condition, input, other) returns an elementwise tensor. At each position it takes input when condition is true and other otherwise; the operands must be broadcastable.
Follow-up: How can torch.where return indices? Use the one-argument form torch.where(condition), which is equivalent to torch.nonzero(condition, as_tuple=True).
condition is a BoolTensor: true or nonzero entries select input, and false entries select other. input and other may each be tensors or scalars.
Follow-up: What determines the output shape? Broadcasting condition, input, and other determines the common output shape.
The optional out keyword supplies the output tensor. The returned tensor has the shape obtained by broadcasting condition, input, and other.
Follow-up: What alternative tensor method is documented? self.where(condition, y) is equivalent to torch.where(condition, self, y).
torch.nonzerotorch.Tensor.where