简体   繁体   中英

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'})

在此处输入图片说明

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

在此处输入图片说明

只需使用:

df.index = ordered_list

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM