Say I have these two arrays:
dictionary = np.array(['a', 'b', 'c'])
array = np.array([['a', 'a', 'c'], ['b', 'b', 'c']])
And I'd like to replace every element in array
with the index of its value in dictionary
. So:
for index, value in enumerate(dictionary):
array[array == value] = index
array = array.astype(int)
To get:
array([[0, 0, 2],
[1, 1, 2]])
Is there a vectorized way to do this? I know that if array
already contained indices and I wanted the strings in dictionary
, I could just do dictionary[array]
. But I effectively need a "lookup" of strings here.
(I also see this answer, but wondering if something new were available since 2010.)