How to Rename Columns in Pandas?

python

To rename specific columns, use df.rename:

import pandas as pd

df = pd.DataFrame({'colA': [1, 2, 3], 'colB': [2, 4, 8]})
df2 = df.rename(columns={"colA": "A", "colB": "B"})
print(df2)

'''Output
   A  B
0  1  2
1  2  4
2  3  8
'''

To rename all columns, set df.columns to list of column names:

import pandas as pd

df = pd.DataFrame({'colA': [1, 2, 3], 'colB': [2, 4, 8]})
df.columns = ["A", "B"]
print(df)

'''Output
   A  B
0  1  2
1  2  4
2  3  8
'''

Latest Questions

python How to Fix ""zsh: command not found: python" Error on MacOS X? python How to Fix "xlrd.biffh.XLRDError: Excel xlsx file; not supported" Error in Pandas? python How to Remove All Whitespace From a Python String?