Reputation: 5559
I have a dataframe df
df
Name
0 A
1 A
2 B
3 B
4 C
5 D
6 E
7 F
8 G
9 H
How can I rename the ideces of the dataframe so that
df
Name
0_A A
1_A A
2_B B
3_B B
4_C C
5_D D
6_E E
7_F F
8_G G
9_H H
Upvotes: 1
Views: 61
Reputation: 862481
1.
Assign to index
concatenated string, first cast it to str
df.index = df.index.astype(str) + '_' + df['Name']
#for remove index name
df.index.name = None
print (df)
Name
0_A A
1_A A
2_B B
3_B B
4_C C
5_D D
6_E E
7_F F
8_G G
9_H H
2.
similar solution with set_index
and rename_axis
:
df = df.set_index(df.index.astype(str) + '_' + df['Name']).rename_axis(None)
print (df)
Name
0_A A
1_A A
2_B B
3_B B
4_C C
5_D D
6_E E
7_F F
8_G G
9_H H
3.
Solution with str.cat
:
df = df.set_index(df.index.astype(str).str.cat(df['Name'], sep='_'))
print (df)
Name
0_A A
1_A A
2_B B
3_B B
4_C C
5_D D
6_E E
7_F F
8_G G
9_H H
4.
list comprehension
solution:
df.index = ['{0[0]}_{0[1]}'.format(x) for x in zip(df.index, df['Name'])]
print (df)
Name
0_A A
1_A A
2_B B
3_B B
4_C C
5_D D
6_E E
7_F F
8_G G
9_H H
Upvotes: 1