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

Generate unique index from existing nonunique index pandas

I have a pandas DataFrame with an index like this:

foo
bar
spam
eggs
foo
bar
spam
eggs

I can access values by using df.loc['foo', 'column'][0], but if I try to set values in the way I get a SettingWithCopyWarning. I need to keep the word descriptions in the index, so is there a way of generating a new index that looks like this?:

foo
bar
eggs
spam
foo_1
bar_1 ... etc.

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 :

Check groupby with cumcount

df.index += df.groupby(level=0).cumcount().mask(lambda x : x==0,'').astype(str)
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