Generate unique index from existing nonunique index pandas

Question:

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.
Asked By: thosphor

||

Answers:

try:

df = pd.DataFrame(index=["bar","spam","eggs","foo"])
#df:
bar
spam
eggs
foo


df['new_col'] = df.index + '_1'
#this will keep the index as it is, and add duplicate column with '_1' suffix
        new_col
bar     bar_1
spam    spam_1
eggs    eggs_1
foo     foo_1
Answered By: khaled koubaa

Check groupby with cumcount

df.index += df.groupby(level=0).cumcount().mask(lambda x : x==0,'').astype(str)
Answered By: BENY
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.