Appending missing values according to index
Say if i have a tensor

values = torch.tensor([5, 3, 2, 8])


and a corresponding index to values

index = torch.tensor([0, 2, 4, 5])


and assuming that I want to insert in the missing index (1 and 3), with a fixed value (100), such that I get

values = torch.tensor([5, 100, 3, 100, 2, 8])


Is there a vectorized way to do it in PyTorch (or numpy)?

You can fill it with 100 first and then fill it with the original values.

in pytorch

import torch

result = torch.empty(6, dtype = torch.int32).fill_(100)
values = torch.tensor([5, 3, 2, 8], dtype = torch.int32)
index = torch.tensor([0, 2, 4, 5])
result[index] = values
print(result)


in numpy

import numpy as np

result = np.full((6,), 100)
index = np.array([0, 2, 4, 5])
values = np.array([5, 3, 2, 8])
result[index] = values
print(result)

