0

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?!

1 Answer 1

1

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')
Sign up to request clarification or add additional context in comments.

2 Comments

please note: I need to do that on 'stringer_index'. 'stringer' is not available. I created only here, that you get an working example.
Thank you! Great As I thought, might be very easy with some aux conversion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.