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)
Answer from johnchase on Stack Overflow
🌐
Medium
medium.com › data-oriented-programming-tips › two-reasons-your-column-renaming-does-not-work-in-pandas-c5f40ecf04aa
Two reasons your column renaming does not work in Pandas | by Danferno | Data Oriented Programming Tips | Medium
August 21, 2023 - # Works (but not recommended) df.rename(columns={'A':'B'}, inplace=True) print(df.columns) # Index(['B'], dtype='object') Yay · I do not recommend ever using the inplace option. It will get you into trouble if you ever swap to a parallel version of Pandas (e.g.
🌐
Reddit
reddit.com › r/learnpython › pandas rename column does not work
r/learnpython on Reddit: Pandas Rename Column does not work
October 6, 2021 -

I have a Pandas dataframe. I have tried three different methods to rename a column, none of which are working. What am I doing wrong? Here is what I have tried:

my_df.columns = my_df.columns.str.replace(' ','_')
my_df.rename(columns={1:"Filing_Date"}, inplace=True)
my_df.rename({"Filing Date": "Filing_Date"}, axis=1, inplace=True)
my_df.dtypes

X                object
Filing Date      object
Trade Date       object
Ticker           object
Company Name     object
Insider Name     object
Title            object
Trade Type       object
Price           float64
Qty             float64
Owned           float64
ΔOwn            float64
Value           float64
dtype: object
🌐
Reddit
reddit.com › r/learnpython › why does this renaming not work?
r/learnpython on Reddit: Why does this renaming not work?
August 4, 2023 -

I am trying to rename the columns without the spaces in between two words for further processing. but the pandas.rename function is not working, and giving the unchanged dataframe. Can anybody please point out what is going wrong here? Thanks.

import pandas as pd

country_column_rename_dict = { 'COUNTRY KEY': 'COUNTRY_KEY', 
                                'COUNTRY NAME': 'COUNTRY_NAME'
} 

data = { 'Country Key': ['NA','AF','LA','GA'],
         'Country Name': ['North America', 'Africa', 'Latin America','Asia'] 
        }

df = pd.DataFrame(data)

df.rename(columns=country_column_rename_dict, inplace=True) print(df)
# Output
Country Key   Country Name
NA            America
AF            Africa
LA           Latin America
GA             Asia

🌐
GitHub
github.com › pandas-dev › pandas › issues › 55169
BUG: Pandas column rename function now working for multilevel columns · Issue #55169 · pandas-dev/pandas
September 16, 2023 - You must be signed in to change notification settings · Fork 19.9k · Star 48.4k · New issueCopy link · New issueCopy link · Open · Open · BUG: Pandas column rename function now working for multilevel columns#55169 · Copy link · Labels · BugMultiIndexrename.rename, .rename_axis.rename, .rename_axis ·
Author: pandas-dev
🌐
GitHub
github.com › pandas-dev › pandas › issues › 49695
df.rename not working with list of dataframes · Issue #49695 · pandas-dev/pandas
November 14, 2022 - I have a list of dataframes, df1,df2 ... df6. I want to rename all columns in these dataframes in the same way. However, when I run through it with a for list, the columns are not changed. Here is my before dataframe: My code: for datafr...
Author: pandas-dev
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.rename.html
pandas.DataFrame.rename — pandas 3.0.6 documentation
Deprecated since version 3.0.0: This keyword is ignored and will be removed in pandas 4.0. Since pandas 3.0, this method always returns a new object using a lazy copy mechanism that defers copies until necessary (Copy-on-Write). See the user guide on Copy-on-Write for more details. ... Whether to modify the DataFrame rather than creating a new one. If True then value of copy is ignored. ... In case of a MultiIndex, only rename labels in the specified level.
🌐
Stack Overflow
stackoverflow.com › questions › 68820100 › pandas-rename-columns-does-not-rename-the-column
Pandas rename columns does not rename the column - Stack Overflow
What worked is this: df.columns.values[27]= 'newName1' This is of course not ideal as it needs to be done individually for each column. As I only had 2 columns to rename this is ok for me.
Find elsewhere
🌐
GitHub
github.com › pandas-dev › pandas › issues › 4160
ENH/BUG: Rename of MultiIndex DataFrames does not work · Issue #4160 · pandas-dev/pandas
July 8, 2013 - xref #14139 for empty MI Hi everybody, in the current version renaming of MultiIndex DataFrames does not work. Lets take the following example: import datetime as DT import pandas as pd df = pd.DataFrame({ 'Branch' : 'A A A A A B'.split(...
Author: pandas-dev
🌐
Pandas
pandas.pydata.org › pandas-docs › version › 0.20 › generated › pandas.DataFrame.rename.html
pandas.DataFrame.rename — pandas 0.20.3 documentation
DataFrame.rename(index=None, columns=None, **kwargs)[source]¶ · Alter axes input function or functions. Function / dict values must be unique (1-to-1). Labels not contained in a dict / Series will be left as-is. Extra labels listed don’t throw an error. Alternatively, change Series.name with a scalar value (Series only). See also · pandas.NDFrame.rename_axis ·
🌐
Pandas
pandas.pydata.org › pandas-docs › version › 0.21.1 › generated › pandas.DataFrame.rename.html
pandas.DataFrame.rename — pandas 0.21.1 documentation
DataFrame.rename(mapper=None, index=None, columns=None, axis=None, copy=True, inplace=False, level=None)[source]¶ · Alter axes labels. Function / dict values must be unique (1-to-1). Labels not contained in a dict / Series will be left as-is. Extra labels listed don’t throw an error. See the user guide for more. See also · pandas.DataFrame.rename_axis ·
🌐
GitHub
github.com › pandas-dev › pandas › issues › 46831
BUG: DataFrame.rename() does not replace existing columns · Issue #46831 · pandas-dev/pandas
April 22, 2022 - DataFrame.rename() does not check if a column already exists. DataFrame.rename() should replace the existing column: ... commit : 4bfe3d0 python : 3.9.10.final.0 python-bits : 64 OS : Linux OS-release : 5.4.0-107-generic Version : #121-Ubuntu SMP Thu Mar 24 16:04:27 UTC 2022 machine : x86_64 processor : x86_64 byteorder : little LC_ALL : None LANG : en_US.UTF-8 LOCALE : en_US.UTF-8 · pandas : 1.4.2 numpy : 1.21.2 pytz : 2021.3 dateutil : 2.8.2 pip : 21.2.4 setuptools : 58.0.4 Cython : None pytest : None hypothesis : None sphinx : 4.4.0 blosc : None feather : None xlsxwriter : None lxml.etree
Author: pandas-dev
🌐
GitHub
github.com › pandas-dev › pandas › issues › 23043
DataFrame.rename() function not throwing Error when non existing column pass in dict · Issue #23043 · pandas-dev/pandas
October 8, 2018 - If rename column found in DataFrame, code renamed it but if rename column not found,Ideally, it should throw KeyError. Function will become more robust . ... Details INSTALLED VERSIONS ------------------ commit: None python: 3.6.1.final.0 python-bits: 64 OS: Linux OS-release: 4.4.0-124-generic machine: x86_64 processor: x86_64 byteorder: little LC_ALL: None LANG: en_IN LOCALE: en_IN.ISO8859-1 · pandas: 0.23.4 pytest: None pip: 18.0 setuptools: 40.0.0 Cython: None numpy: 1.15.0 scipy: None pyarrow: None xarray: None IPython: 6.5.0 sphinx: None patsy: None dateutil: 2.7.3 pytz: 2018.5 blosc: None bottleneck: None tables: None numexpr: None feather: None matplotlib: None openpyxl: None xlrd: None xlwt: None xlsxwriter: None lxml: None bs4: None html5lib: 1.0.1 sqlalchemy: None pymysql: 0.9.2 psycopg2: None jinja2: 2.10 s3fs: None fastparquet: None pandas_gbq: None pandas_datareader: None
Author: pandas-dev
🌐
Built In
builtin.com › data-science › rename-columns-pandas
How to Rename Columns in Pandas | Built In
More on PandasLoc and iLoc Functions in Pandas Tutorial · This method is originally used to set labels to DataFrame’s axis, i.e. this method can be used to label columns as well as rows. All you need to do is simply pass the list of column names to the .set_axis() function and specify axis = 1 to rename columns, like below:
🌐
datagy
datagy.io › home › pandas tutorials › pandas dataframes › how to rename pandas dataframe columns (with examples)
How to Rename Pandas DataFrame Columns (with Examples) • datagy
December 15, 2022 - # Raising an Error When Renaming Columns import pandas as pd df = pd.DataFrame.from_dict({ 'Name': ['Jane', 'Melissa', 'John', 'Matt'], 'Age': [23, 45, 35, 64], 'Age Group': ['18-35', '35-50', '35-50', '65+'], 'Birth City': ['London', 'Paris', 'Toronto', 'Atlanta'], 'Gender': ['Female', 'Female', 'Male', 'Male']}) df = df.rename(columns={'some silly name': 'column1'}, errors='raise') print(df) # Returns: # KeyError: "['some silly name'] not found in axis" We can see that by using the errors= parameter, that we can force Python to raise errors when a column label doesn’t exist. The .rename() method also includes an argument to specify which level of a multi-index you want to rename. A common occurrence of multi-index Pandas DataFrames is when working with pivot tables.
🌐
Codecademy Forums
discuss.codecademy.com › data science
Pandas series.rename not updating dataframe.column names - Data Science - Codecademy Forums
March 4, 2023 - I’m working on the jeopardy task (https://www.codecademy.com/journeys/data-scientist-aly/paths/dsalycj-22-data-science-foundations-ii/tracks/dsalycj-22-pandas-for-data-science/modules/dsf-data-manipulation-challenge-project-6cc2e59c-5bbc-46e7-bf81-3c88ace67247/projects/this-is-jeopardy) which starts with loading in a provided csv that is “unclean” The first issue i started to tackle was the white space in the column headers… and i’ve come across something that has baffled me. df = pd.read_csv(...
🌐
Python Forum
python-forum.io › thread-40610.html
Cannot rename Columns in df
August 25, 2023 - Greetings! I need to rename Columns in the Dataframe. I found if the name has a space my script is failing. I tried a lot of examples from the Net and nothing is working for some reason. Column Names are staying the same. **sad** here is a 'renaming...
Top answer
1 of 3
4

df.rename fails here, because it tries to map labels per level. You can use pd.Index.map with dict.get:

df_test.columns = df_test.columns.map(lambda col: test_map.get(col, col))

Result:

df_test.columns

MultiIndex([('Group_A', 'Current_1'),
            ('Group_A', 'Current_2'),
            ('Group_B', 'Current_1'),
            ('Group_B',  'Metric_2')],
           )

Alternative assignment possible via df.set_axis:

df_test = df_test.set_axis(
    df_test.columns.map(lambda col: test_map.get(col, col)), axis=1
    )
2 of 3
1

The rename method in pandas generally operates on the labels of specific levels when dealing with a MultiIndex, rather than treating the full column tuples as single keys. Because of this, passing a dictionary of tuples often fails to match the columns as you intend.

To solve this, the most reliable approach is to rebuild the index using a list comprehension or map to apply your dictionary, and then assign it back to df.columns.

When df.rename(columns=...) is called on a MultiIndex, pandas attempts to align the dictionary keys with the labels of the index levels, not the composite tuples (pairs).Since your keys are tuples and the level labels are individual strings, no match is found, and nothing changes.

import pandas as pd

cols = pd.MultiIndex.from_tuples([
    ('Group_A', 'Metric_1'), 
    ('Group_A', 'Metric_2'), 
    ('Group_B', 'Metric_1'), 
    ('Group_B', 'Metric_2')
])
df_test = pd.DataFrame([
    [10, 20, 30, 40], 
    [50, 60, 70, 80]
], columns=cols)

test_map = {
    ('Group_A', 'Metric_1'): ('Group_A', 'Current_1'),
    ('Group_A', 'Metric_2'): ('Group_A', 'Current_2'),
    ('Group_B', 'Metric_1'): ('Group_B', 'Current_1')
}

# --- Solution ---
# Create a new list of columns by looking up each tuple in your map;
# if it's not in the map, keep the original tuple.
new_columns = [test_map.get(col, col) for col in df_test.columns]

# Assign the new columns back to the DataFrame
df_test.columns = pd.MultiIndex.from_tuples(new_columns)

print("--- Check Results ---")
print(df_test.columns.tolist())