rename a column in pandas in python

To rename a column in Pandas, you can use the rename method. You can either rename a single column or multiple columns at once. Here's the syntax:

To rename a single column:

main.py
import pandas as pd

df = pd.read_csv('path/to/file.csv')
df = df.rename(columns={'old_col_name': 'new_col_name'})
115 chars
5 lines

To rename multiple columns:

main.py
import pandas as pd

df = pd.read_csv('path/to/file.csv')
df = df.rename(columns={'old_col_name_1': 'new_col_name_1', 'old_col_name_2': 'new_col_name_2'})
155 chars
5 lines

Note that the rename method returns a new DataFrame, so you should assign the result back to the original variable to update it.

related categories

gistlibby LogSnag