Would torch.where work for you? torch.where — PyTorch 1.10.0 documentation
However, I’m not familiar with the implementation details/potential performance tradeoffs, so you might want to check the final speed of whatever approach you go with (e.g., just because one approach only does a single read of data/comparison doesn’t mean it is guaranteed to be faster).