0

I have a dataframe like this. I wanted to know how can I apply map function to its index and rename it into a easier format.

df = pd.DataFrame({'d': [1, 2, 3, 4]}, index=['apple_017', 'orange_054', 'orange_061', 'orange_053'])
df
             d
apple_017    1
orange_054    2
orange_061    3
orange_053    4

There are only two labels in the indeces of the dataframe, so it's either apple or orange in this case and this is how I tried:

data.index = data.index.map(i = "apple" if "apple" in i else "orange")

(Apparently it's not how it works)

Desired output:

         d
apple    1
orange    2
orange    3
orange    4

Appreciate anyone's help and suggestion!

1 Answer 1

1

Try via split():

df.index=df.index.str.split('_').str[0]

OR

via map():

df.index=df.index.map(lambda x:'apple' if 'apple' in x else 'orange')

output of df:

        d
apple   1
orange  2
orange  3
orange  4
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for helping out! That's exactly what I want

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.