Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 226
The Great Avatar asked Aug 12 '26 05:08

The Great


1 Answers

Just use:

df.index = ordered_list
like image 73
U12-Forward Avatar answered Aug 15 '26 07:08

U12-Forward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!