Use set_levels:
In [22]:
df.columns.set_levels(['b1','c1','f1'],level=1,inplace=True)
df
Out[22]:
a d
b1 c1 f1
0 1 2 3
1 10 20 30
2 100 200 300
rename sets the name for the index, it doesn't rename the column names:
In [26]:
df.columns = df.columns.rename("b1", level=1)
df
Out[26]:
a d
b1 b c f
0 1 2 3
1 10 20 30
2 100 200 300
This is why you get the error
Answer from EdChum on Stack Overflow Top answer 1 of 8
91
Use set_levels:
In [22]:
df.columns.set_levels(['b1','c1','f1'],level=1,inplace=True)
df
Out[22]:
a d
b1 c1 f1
0 1 2 3
1 10 20 30
2 100 200 300
rename sets the name for the index, it doesn't rename the column names:
In [26]:
df.columns = df.columns.rename("b1", level=1)
df
Out[26]:
a d
b1 b c f
0 1 2 3
1 10 20 30
2 100 200 300
This is why you get the error
2 of 8
69
In pandas 0.21.0+ use parameter level=1:
d = dict(zip(df.columns.levels[1], ["b1", "c1", "f1"]))
print (d)
{'c': 'c1', 'b': 'b1', 'f': 'f1'}
df = df.rename(columns=d, level=1)
print (df)
a d
b1 c1 f1
0 1 2 3
1 10 20 30
2 100 200 300
Pandas
pandas.pydata.org › pandas-docs › version › 0.22 › generated › pandas.MultiIndex.rename.html
pandas.MultiIndex.rename — pandas 0.22.0 documentation
>>> Index([1, 2, 3, 4]).set_names('foo') Int64Index([1, 2, 3, 4], dtype='int64') >>> Index([1, 2, 3, 4]).set_names(['foo']) Int64Index([1, 2, 3, 4], dtype='int64') >>> idx = MultiIndex.from_tuples([(1, u'one'), (1, u'two'), (2, u'one'), (2, u'two')], names=['foo', 'bar']) >>> idx.set_names(['baz', 'quz']) MultiIndex(levels=[[1, 2], [u'one', u'two']], labels=[[0, 0, 1, 1], [0, 1, 0, 1]], names=[u'baz', u'quz']) >>> idx.set_names('baz', level=0) MultiIndex(levels=[[1, 2], [u'one', u'two']], labels=[[0, 0, 1, 1], [0, 1, 0, 1]], names=[u'baz', u'bar'])
ENH: Rename multi-level columns or indices using their tupelized names
It's currently quite difficult to rename a single column (or row) in a multi-indexed DataFrame. The problem is illustrated also in this SO article. The current approach requires at least 3 step... More on github.com
python - Pandas - Create Multiindex columns during rename - Stack Overflow
I'm trying to find a simple way to rename a flat column index to a hierarchical multindex column set. I've come across one way, but it seems a bit kludgy - is there a better way to do this in Panda... More on stackoverflow.com
python - pandas multiindex columns rename - Stack Overflow
hi I would like to rename the columns of my df. it has a multiindex columns and I would like to change the second level of it ie I have : ('GDP US Chained 2012 Dollars SAAR', 'GDP CHWG Index') ('G... More on stackoverflow.com
python - Rename unnamed multiindex columns in Pandas DataFrame - Stack Overflow
1 Pandas dataframes with multi-level columns:rename a specific level of column so that it's same as another level More on stackoverflow.com
TutorialsPoint
tutorialspoint.com › python_pandas › python_pandas_renaming_multiindex_labels.htm
Python Pandas - Renaming MultiIndex Labels
To rename the labels of the index or columns in a MultiIndexed object, you can use the pandas DataFame.rename() method.
GitHub
github.com › pandas-dev › pandas › issues › 38069
ENH: Rename multi-level columns or indices using their tupelized names · Issue #38069 · pandas-dev/pandas
November 25, 2020 - df = pd.DataFrame([[1,2,3],[3,4,5],[5,6,7], [7,8,9]]) df.columns = pd.MultiIndex.from_tuples([('i','a'),('i','b'),('ii','a')]) # Rename using tuples: df.rename(columns={('i','b'):('ii','b')}) # Rename using current column name (equivalent to 1a) col = df[('i','b')] df.rename(columns={col.name: ('ii','b')})
Author pandas-dev
Saturn Cloud
saturncloud.io › blog › how-to-rename-multiindex-columns-in-pandas-a-guide-for-data-scientists
How to Rename MultiIndex Columns in Pandas A Guide for Data Scientists | Saturn Cloud Blog
June 19, 2023 - Testing: Before applying renaming to the entire dataset, conduct testing on a small subset to validate the correctness of the renaming logic. This reduces the risk of errors on the entire dataset. Working with MultiIndex columns in Pandas can be challenging, especially when dealing with large datasets.
Pandas
pandas.pydata.org › docs › user_guide › advanced.html
MultiIndex / advanced indexing — pandas 3.0.3 documentation
The rename() method is used to rename the labels of a MultiIndex, and is typically used to rename the columns of a DataFrame.
Solix Technologies
solix.com › products › answers › renaming-multiindex-columns-in-pandas-a-data-science-guide
Renaming MultiIndex Columns In Pandas - A Data Science Guide | Solix Technologies, Inc.
June 29, 2025 - One of the simplest ways to rename your MultiIndex columns is by using the setnames method. This method allows you to explicitly name the levels of your MultiIndex. Heres a practical example · import pandas as pd Create a sample DataFrame with MultiIndexarrays = A, A, B, B, one, two, one, ...
Apache
spark.apache.org › docs › latest › api › python › reference › pyspark.pandas › api › pyspark.pandas.MultiIndex.rename.html
pyspark.pandas.MultiIndex.rename — PySpark 4.1.1 documentation
>>> df = ps.DataFrame({'a': ['A', 'C'], 'b': ['A', 'B']}, columns=['a', 'b']) >>> df.index.rename("c") Index([0, 1], dtype='int64', name='c') >>> df.set_index("a", inplace=True) >>> df.index.rename("d") Index(['A', 'C'], dtype='object', name='d') You can also change the index name in place. >>> df.index.rename("e", inplace=True) >>> df.index Index(['A', 'C'], dtype='object', name='e') ... >>> psidx = ps.MultiIndex.from_tuples([('a', 'x'), ('b', 'y')]) >>> psidx.names = ['hello', 'pandas-on-Spark'] >>> psidx MultiIndex([('a', 'x'), ('b', 'y')], names=['hello', 'pandas-on-Spark'])
Top answer 1 of 2
2
You could try:
df.columns = pd.MultiIndex.from_tuples(df.rename(columns = nested_columns).columns)
df
Output:
One Two
a c b d
0 27 67 35 36
1 80 42 93 20
2 64 9 18 83
3 85 69 60 84
2 of 2
1
IIUC, rename
flat_df.rename(columns=nested_columns)
Out[224]:
One Two
a c b d
0 36 19 53 46
1 17 85 63 36
2 40 80 75 86
3 31 83 75 16
Updated
flat_df.columns.map(nested_columns.get)
Out[15]:
MultiIndex(levels=[['One', 'Two'], ['a', 'b', 'c', 'd']],
labels=[[0, 0, 1, 1], [0, 2, 1, 3]])
DevPress
devpress.csdn.net › bigdata › 62f253767e6682346618506d.html
How to Rename Multi index columns in Pandas Dataframe_python_weixin_0010034-大数据
In this short tutorial, you've learnt how to rename the columns of the multi-index pandas data-frame using the set_levels() method.
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.rename.html
pandas.DataFrame.rename — pandas 3.0.3 documentation
In case of a MultiIndex, only rename labels in the specified level. errors{‘ignore’, ‘raise’}, default ‘ignore’ · If ‘raise’, raise a KeyError when a dict-like mapper, index, or columns contains labels that are not present in the Index being transformed.
Stack Overflow
stackoverflow.com › questions › 74517802 › pandas-multiindex-columns-rename
python - pandas multiindex columns rename - Stack Overflow
df.columns = pd.MultiIndex.from_tuples([ (col0, col1.lower().replace('index', ''), *more_cols) for col0, col1, *more_cols in df.columns], names=df.columns.names)
codestudy
codestudy.net › blog › renaming-index-values-in-multiindex-dataframe
How to Rename Index Values in a Pandas MultiIndex DataFrame: Step-by-Step Guide with Examples — codestudy.net
To rename values in either level (e.g., change "Q1" to "Q1 (Jan-Mar)"), we need targeted methods to avoid breaking the hierarchy. Let’s create a sample MultiIndex DataFrame to use in our examples. We’ll use sales data with Year (2022-2023) and Quarter (Q1-Q4) as index levels: import pandas as pd # Sample data data = { "Sales": [100, 200, 150, 300, 250, 350, 400, 500], "Expenses": [50, 100, 75, 150, 125, 175, 200, 250] } # Create MultiIndex (Year, Quarter) index_tuples = [ ("2022", "Q1"), ("2022", "Q2"), ("2022", "Q3"), ("2022", "Q4"), ("2023", "Q1"), ("2023", "Q2"), ("2023", "Q3"), ("2023", "Q4") ] multi_index = pd.MultiIndex.from_tuples(index_tuples, names=["Year", "Quarter"]) # Create DataFrame df = pd.DataFrame(data, index=multi_index) print(df)
Top answer 1 of 3
6
Since pandas 0.21.0 the code should be like this
def rename_unnamed(df):
"""Rename unamed columns name for Pandas DataFrame
See https://stackoverflow.com/questions/41221079/rename-multiindex-columns-in-pandas
Parameters
----------
df : pd.DataFrame object
Input dataframe
Returns
-------
pd.DataFrame
Output dataframe
"""
for i, columns in enumerate(df.columns.levels):
columns_new = columns.tolist()
for j, row in enumerate(columns_new):
if "Unnamed: " in row:
columns_new[j] = ""
if pd.__version__ < "0.21.0": # https://stackoverflow.com/a/48186976/716469
df.columns.set_levels(columns_new, level=i, inplace=True)
else:
df = df.rename(columns=dict(zip(columns.tolist(), columns_new)),
level=i)
return df
2 of 3
4
Mixing answers from @jezrael and @dinya, and limited for pandas above 0.21.0 (after 2017) an option to solve this will be:
for i, columns_old in enumerate(df.columns.levels):
columns_new = np.where(columns_old.str.contains('Unnamed'), '-', columns_old)
df.rename(columns=dict(zip(columns_old, columns_new)), level=i, inplace=True)
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 - Here I attempt to rename the columns, which should now be tuples with ticker symbols instead of company names.
Author pandas-dev