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]
1
  • 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. Commented Oct 20, 2019 at 3:37

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

2 Comments

You missed return_count argument
@tstanisl. Wow. Much appreciated :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.