1

I have the following Pandas data frame:

import pandas as pd
df = pd.DataFrame({'d': [1, 2, 3]}, index=['FOO', 'BAR', 'BAZ'])
df
        d
FOO     1
BAR     2
BAZ     3

What I want to do is to append two strings in front of the index.

str1 = "x"
str2 = "y"

Yielding:

            d
x_y.FOO     1
x_y.BAR     2
x_y.BAZ     3

How can I do that?

3
  • 1
    df.index="x_y."+df.index or df.index=str1+'_'+str2+df.index? Commented Jul 29, 2021 at 3:26
  • 1
    df.index=f"{str1}_{str2}."+df.index Commented Jul 29, 2021 at 3:30
  • @scamander hadn't my answer solved your problem? You haven't responded anything. Commented Jul 29, 2021 at 4:14

1 Answer 1

3

You can try this:

import pandas as pd
df = pd.DataFrame({'d': [1, 2, 3]}, index=['FOO', 'BAR', 'BAZ'])
print(df)
"""
        d
FOO     1
BAR     2
BAZ     3
"""
str1 = "x"
str2 = "y"
df.index=f"{str1}_{str2}."+df.index
print(df)
"""
         d
x_y.FOO  1
x_y.BAR  2
x_y.BAZ  3
"""

We are just adding that same string in all of the index of df. You can explore for about index from here

Note : This will only work if index is already str this wouldn't work on a RangeIndex without

df.index.astype(str)
Sign up to request clarification or add additional context in comments.

Comments

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.