2

I have the dataframe df

import pandas as pd
b=np.array([0,1,2,2,0,1,2,2,3,4,4,4,5,6,0,1,0,0]).reshape(-1,1)
c=np.array(['a','a','a','a','b','b','b','b','b','b','b','b','b','b','c','c','d','e']).reshape(-1,1)
df = pd.DataFrame(np.hstack([b,c]),columns=['Start','File'])


df
Out[22]: 
   Start File
0      0    a
1      1    a
2      2    a
3      2    a
4      0    b
5      1    b
6      2    b
7      2    b
8      3    b
9      4    b
10     4    b
11     4    b
12     5    b
13     6    b
14     0    c
15     1    c
16     0    d
17     0    e

I would like to rename the index using index_File in order to have 0_a, 1_a, ...17_e as indeces

2 Answers 2

4

You use set_index with or without the inplace=True

df.set_index(df.File.radd(df.index.astype(str) + '_'))

     Start File
File           
0_a      0    a
1_a      1    a
2_a      2    a
3_a      2    a
4_b      0    b
5_b      1    b
6_b      2    b
7_b      2    b
8_b      3    b
9_b      4    b
10_b     4    b
11_b     4    b
12_b     5    b
13_b     6    b
14_c     0    c
15_c     1    c
16_d     0    d
17_e     0    e

At the expense of a few more code characters, we can quicken this up and take care of the unnecessary index name

df.set_index(df.File.values.__radd__(df.index.astype(str) + '_'))

     Start File
0_a      0    a
1_a      1    a
2_a      2    a
3_a      2    a
4_b      0    b
5_b      1    b
6_b      2    b
7_b      2    b
8_b      3    b
9_b      4    b
10_b     4    b
11_b     4    b
12_b     5    b
13_b     6    b
14_c     0    c
15_c     1    c
16_d     0    d
17_e     0    e
Sign up to request clarification or add additional context in comments.

Comments

3

You can directly assign to the index, first by converting the default index to str using astype and then concatenate the str as usual:

In[41]:
df.index = df.index.astype(str) + '_' + df['File']
df

Out[41]: 
     Start File
File           
0_a      0    a
1_a      1    a
2_a      2    a
3_a      2    a
4_b      0    b
5_b      1    b
6_b      2    b
7_b      2    b
8_b      3    b
9_b      4    b
10_b     4    b
11_b     4    b
12_b     5    b
13_b     6    b
14_c     0    c
15_c     1    c
16_d     0    d
17_e     0    e

1 Comment

So I don't usually see answers evolve as they're first written, but I watched this. Looks like you first posted a minimally working solution, then you fixed it up a touch, then you added some description of what you did at the top?

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.