any similar function like df.mask for tensor in pytorch?
I want to replace all 0s in a 2-D tensor with -5. 

With dataframe, i can easily do this:

df = df.mask(df=0, -5) 


but this does not work for tensors. I have tried: 

 y = torch.where(y = 0, -5, y) 


There are two general ways.

One, given above by prhmma is to use in-place mutation like y[y == 0] = -5. It is nice and efficient, but will break autograd operation. So if you want gradient to flow through y, you should not do that.

The other is to use torch.where, as you have attempted. The proper incantation is

y = torch.where(y == 0, torch.tensor(-5), y)


or, if you want to be device- and dtype-agnostic

five = torch.tensor(-5, dtype=y.dtype, device=y.device)
y = torch.where(y == 0, five, y)


the fact that where does not accept scalars is an annoying papercut, but that's how it is ATM. Note that while the choice itself is discrete and obviously not differentiable, this operation will let gradients flow through both operands.
