0

I have a question regarding Numpy arrays (the answer should include them). I want to create and array where each element will be mapped into a specific integer. Here is the code I got until now:

array1 = np.array(['dog', 'cat', 'parrot', 'parrot', 'dog'])
array2 = (np.unique(array1))
for index, key in enumerate(array2):
     print(np.where(array1 == key, index+1, 0))

The output now is:

[1 0 0 0 1]
[0 2 0 0 0]
[0 0 3 3 0]

But I want it to be just

[1 2 3 3 1] 
3
  • Note that you usually want to avoid iterating over a NumPy array, and use it's vectorised approach (including broadcasting where necessary). Commented Sep 20, 2021 at 15:26
  • Depending on the final goal, you could actually use scikit-learn's OrdinalEncoder. Commented Sep 20, 2021 at 15:29
  • Not sure the title matches the problem you want solved. How about 'How to make integer index of unique values in Numpy array?' Commented Sep 20, 2021 at 15:36

1 Answer 1

1

If you're not too picky about the exact value of the integer (just that they are unique and match a string one-to-one):

array1 = np.array(['dog', 'cat', 'parrot', 'parrot', 'dog'])
result = np.unique(array1, return_inverse=True)[1] + 1

(The + 1 is there so that it matches your result, since you also have index+1 in the original code.)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.