Filter nan values based on two tensors

I have 2 pytorch tensors say as follows:

x = torch.Tensor([float('nan'), 2.0, 5.0, 6.0])
y = torch.Tensor([float('nan'), float('nan'), 3.0, 4.0])

I want to filter both the arrays where entries that are NAN in either of the two arrays are filtered out i.e. in this case,

filtered_x = [5., 6.]
filtered_y = [3., 4.]

Just wondering how one can do it with pytorch. I am also using a rather old version of pytorch 1.0.1.post2

tensor.is_finite should work:

x = torch.Tensor([float('nan'), 2.0, 5.0, 6.0])
y = torch.Tensor([float('nan'), float('nan'), 3.0, 4.0])

idx = x.isfinite() &  y.isfinite()
out = torch.stack((x[idx], y[idx]))
print(out)
# tensor([[5., 6.],
#         [3., 4.]])

I don’t know if this method is available in the old 1.0.1 version so you might need to update or write a method to check for finite values.

1 Like

Thank you. I could just use torch.isfinite()