Renaming the column names of pandas dataframe is not working as expected - python

 ̄綄美尐妖づ 提交于 2021-02-18 06:43:28

问题


I am having below pandas dataframe df. I am trying to rename the column names but it not working as expected.

Code:

 mapping = {df.columns[0]:'Date', df.columns[1]: 'A', df.columns[2]:'B', df.columns[3]: 'C',df.columns[4]:'D', df.columns[5]: 'E',df.columns[6]:'F', df.columns[7]: 'G',df.columns[8]:'H', df.columns[9]: 'J'}
 df.rename(columns=mapping) 

Output of df.columns:

MultiIndex(levels=[['A Index', 'B Index', 'C Index', 'D Index', 'E Index', 'F Index', 'G Index', 'H Index', 'I Index', 'J Index', 'K Index', 'L Index', 'M Index', 'N Index', 'O Index', 'date', 'index'], ['PX_LAST', '']],
       labels=[[16, 15, 11, 9, 10, 6, 3, 4, 2, 5, 14, 1, 13, 12, 7, 0, 8], [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
       names=['ticker', 'field'])

Even after running the code, column name stays the same. Can anyone help rename column names of this dataframe.


回答1:


Because you know the order of the columns already why not just use:

df.columns = ['Date', 'a', 'b', 'c', 'd', 'e', 'f' 'g', 'h', 'i', 'j']

Otherwise if you want to use rename you will need to assign it to a variable:

 mapping = {df.columns[0]:'Date', df.columns[1]: 'A', df.columns[2]:'B', df.columns[3]: 'C',df.columns[4]:'D', df.columns[5]: 'E',df.columns[6]:'F', df.columns[7]: 'G',df.columns[8]:'H', df.columns[9]: 'J'}
 df = df.rename(columns=mapping)


来源:https://stackoverflow.com/questions/47060980/renaming-the-column-names-of-pandas-dataframe-is-not-working-as-expected-pytho

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