0

Is there a simple way to do this in Python?

For example I have:

x = np.array(['a', 'b', 'a', 'b', 'b', 'u'])

Desired outcome:

[2, 3, 2, 3, 3, 1]
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
  • You can select an answer even after your question is closed. I'd recommend doing so, since the relatively new arguments to np.unique make the answer more efficient than the accepted one of the duplicate. – Mad Physicist Oct 20 '19 at 03:37

1 Answers1

3

Use np.unique with return_counts and return_inverse enabled:

_, inverse, count = np.unique(x, return_inverse=True, return_count=True)
result = count[inverse]
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264