The Great
The Great

Reputation: 7743

How to rename dataframe index efficiently using a python list?

I have a pandas dataframe and a ordered list like as shown below

df = pd.DataFrame([[1, 2, 3], [4, 5 ,6]], columns=list('ABC'))
df = df.rename(index={0:'x1'})
df = df.rename(index={1:'x2'})

enter image description here

Please note that I already refer post

The list looks like as shown below

ordered_list = ['Name_1','Name_2']

This is what I was trying but it is not efficient and cannot be used for a dataframe with more records

df = df.rename(index={'x1':'Name_1'})
df = df.rename(index={'x2':'Name_2'})

You can see that I have renamed the index using rename function. But is there anyway to do this efficiently using the ordered list available? Because my real data has more than 60 index values

I mean first element in the list corresponds to x1 and 2nd element in the list corresponds to x2 etc.

I expect my output to look like as shown below

enter image description here

Upvotes: 3

Views: 1538

Answers (2)

oppressionslayer
oppressionslayer

Reputation: 7222

You can do this, then you wont need an ordered list:

df.index = df.reset_index().index+1
df = df.T.add_prefix('Name_').T

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71620

Just use:

df.index = ordered_list

Upvotes: 2

Related Questions