I have following 2D numpay array:
matrix = np.array([
[ 0, 1, 4, 3],
[ 1, 2, 5, 4],
[ 3, 4, 7, 6],
[ 4, 5, 8, 7],
[ 2, 10, 13, 5],
[10, 11, 14, 13],
[ 5, 13, 16, 8],
[13, 14, 17, 16],
[18, 19, 22, 21],
[19, 11, 10, 22],
[21, 22, 1, 0],
[22, 10, 2, 1]])
I have another array which carries the values that I want to replace inside matrix.
substitutes = np.array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 13, 14, 16, 17, 18, 19, 21, 22])
Find the indices of each of the substitutes inside matrix (multiple occurrences are possible):
indices = [np.argwhere(s == matrix) for s in substitutes]
Then I do:
matrix_renumbered = copy.deepcopy(matrix)
for i, indices_per_value in enumerate(indices):
for index in indices_per_value:
# the substitutes are replaced just by the counter i (to be contiguous)
matrix_renumbered[index[0], index[1]] = i
Expected result:
array([[ 0, 1, 4, 3],
[ 1, 2, 5, 4],
[ 3, 4, 7, 6],
[ 4, 5, 8, 7],
[ 2, 9, 11, 5],
[ 9, 10, 12, 11],
[ 5, 11, 13, 8],
[11, 12, 14, 13],
[15, 16, 18, 17],
[16, 10, 9, 18],
[17, 18, 1, 0],
[18, 9, 2, 1]])
Is there a better way (e.g. using numpy) to do what the double for-loop does?
Andy