Home >Backend Development >Python Tutorial >How Can I Rename Columns in a Pandas DataFrame?
To change the column labels of a Pandas DataFrame, a number of methods are available.
Use the df.rename() function to specify the columns to be renamed:
df = df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'}) # Or rename the existing DataFrame df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'}, inplace=True)
Use df.set_axis() with axis=1 to reassign the column headers:
df2 = df.set_axis(['V', 'W', 'X', 'Y', 'Z'], axis=1)
Headers can also be assigned directly:
df.columns = ['V', 'W', 'X', 'Y', 'Z']
Minimal Code Example
To rename the columns of a DataFrame from ['a', '$b', '$c', '$d', '$e'] to ['a', 'b', 'c', 'd', 'e']:
import pandas as pd df = pd.DataFrame('x', index=range(3), columns=list('abcde')) df2 = df.rename(columns={'$b': 'b', '$c': 'c', '$d': 'd', '$e': 'e'}) print(df2)
Output:
a b c d e 0 x x x x x 1 x x x x x 2 x x x x x
The above is the detailed content of How Can I Rename Columns in a Pandas DataFrame?. For more information, please follow other related articles on the PHP Chinese website!