Nathan Klein
Nathan Klein

Reputation: 11

Relabeling all indices on pandas

I have an xslx file which I've set its' ID column to be my index on pandas.

Index starts at 3200 up to 3509. I'm requested to relabel all of my index values meaning, ID column value so that each index has a prefix named sub_. For example, for index 3200, I'm requested to change it to sub_3200 and so on and so forth.

I've tried using reindex, after creating a dictionary in which all of the values are the modified names ('sub_3200', ...). I tried reindexing using dictionary.values(), which does change the labels of the indices, however all of the other values in the data frame now appear as NaN, even though there were values before hand.

How can I relabel my index without harming the rest of the data frame?

Upvotes: 1

Views: 81

Answers (1)

piRSquared
piRSquared

Reputation: 294218

Hack

df.T.add_prefix('sub_').T

Less Hack

df.set_index('sub_' + df.index.astype(str))

Upvotes: 2

Related Questions