[ad_1]
Say I have the following labels and target values:
labels = np.array([[0, 0, 2],
[1, 1, 2],
[1, 1, 2]])
targets = np.array([9, 4, 7])
I want to generate a new array, where I replace value i
in labels with targets[i]
. Here is a possible solution:
n_labels = np.max(labels) + 1
out = np.empty(labels.shape)
for i in range(n_labels):
mask = labels == i
out[mask] = targets[i]
>>> out
np.array([[9, 9, 7],
[4, 4, 7],
[4, 4, 7]])
However, as the size of labels
and targets
grow, I see this solution as being inefficient. Each iteration, only a small number of values of out
are being populated. However, each iteration, this approach computes the mask over all of labels
(in the expression labels == i
) and subsequently indexes over all of out
(in the expression out[mask]
). Is there a more efficient way to do this?
[ad_2]