Rockbar
Rockbar

Reputation: 1161

Replace string elements in pandas Index object

I have a very simple problem, but cannot find an answer. I have a pandas Index object containing strings ('string_index'). I want to replace certain elements, by preferrably a dictionary, in this string Index

 [In:] string_index
 [Out:] Index(['A', 'B', 'C', 'D', 'E', 'F'], dtype='object')

 exchange_dict = {'A':'Y', 'B':'Z'}

But trying

 string_index.rename(exchange_dict)

does not work and method .replace is not possible. How can I do that?

To get 'string_index' here as example:

 string_list=['A', 'B', 'C', 'D', 'E', 'F']
 stringer = pd.DataFrame(string_list, index=string_list)
 string_index = stringer.index

Please note: 'stringer_list' and 'stringer' are not part of the challenge, I only created to give you a working example. In my real example I only have 'string_index'. I suppose there is a very easy solution, I am too dumb to find?!

Upvotes: 0

Views: 893

Answers (1)

BENY
BENY

Reputation: 323226

You need to mention index in rename

stringer.rename(index=exchange_dict)
Out[557]: 
   0
Y  A
Z  B
C  C
D  D
E  E
F  F

Update

pd.Index(string_index.to_series().replace(exchange_dict))
Out[570]: Index(['Y', 'Z', 'C', 'D', 'E', 'F'], dtype='object')

Upvotes: 1

Related Questions