Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I remap a Python Pandas Series of ints to 0,1,2,3,4 based on their order from smallest to largest?

I would like to remap a Python Pandas Series of ints to 0,1,2,3,4,… based on their order from smallest to largest. Equal ints should be mapped to the same int.

For example, if I have a pandas Series [1, 1, 4, 4, 7, 12, 18, 18], I would like it mapped to [0, 0, 1, 1, 2, 3, 4, 4]. Basically it’s like squishing the ints so that they’re next to each other.

I’ve tried converting to a standard list and using a naive implementation, but wondering if there’s a more idiomatic way to do it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use pd.Categorical:

s = pd.Series([1, 1, 4, 4, 7, 12, 18, 18])

print(pd.Categorical(s).codes)

Prints:

[0 0 1 1 2 3 4 4]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading