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