Renaming selected columns in pandas [duplicate]

不问归期 提交于 2021-02-10 12:07:49

问题


I am trying to rename selected columns (say the two las columns) in my data frame using the iloc and df.columns functions but it does not seem to work for me and I can't figure out why. Here is a toy example of what I want to achieve:

import pandas as pd

d = {'one': list(range(5)),
     'two': list(range(5)),
     'three': list(range(5)),
     'four': list(range(5)),
     'five': ['a', 'b', 'c', 'd', 'e'],
     'six': ['a', 'b', 'c', 'd', 'e']
    }
df = pd.DataFrame(d)

df.iloc[:,-2:].columns = ['letter_1','letter_2']

df.columns

but I keep getting the original columns' names:

Index(['one', 'two', 'three', 'four', 'five', 'six'], dtype='object')

What am I missing?


回答1:


just use df.rename:

import pandas as pd

d = {'one': list(range(5)),
     'two': list(range(5)),
     'three': list(range(5)),
     'four': list(range(5)),
     'five': ['a', 'b', 'c', 'd', 'e'],
     'six': ['a', 'b', 'c', 'd', 'e']
     }

new_names = ['letter_1', 'letter_2']
df = pd.DataFrame(d).rename(index=str, columns=dict(zip(list(d.keys())[-len(new_names):], new_names)))

print(df.columns)

Output:

Index(['letter_1', 'four', 'one', 'letter_2', 'three', 'two'], dtype='object')



来源:https://stackoverflow.com/questions/56790037/renaming-selected-columns-in-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!