3/30/2018 - 3:32 AM

Pandas - Rename Columns

How do I rename columns in a Pandas DataFrame.

import pandas as pd

ufo = pd.read_csv('')

# Index(['City', 'Colors Reported', 'Shape Reported', 'State', 'Time'], dtype='object')

ufo.rename(columns={'Colors Reported': 'Colors_Reported',
                    'Shape Reported': 'Shape_Reported'}, inplace=True)
# Index(['City', 'Colors_Reported', 'Shape_Reported', 'State', 'Time'], dtype='object')

# OR

ufo_cols = ['city', 'colors reported', 'shape reported', 'state', 'time']
ufo.columns = ufo_cols
# Index(['city', 'colors reported', 'shape reported', 'state', 'time'], dtype='object')

# OR
ufo = pd.read_csv('',
                  names=ufo_cols,   # Passing a list of columns names as parameter.
                  header=0)         # Set to 0 if csv or tsv has a header by default.

ufo.columns = ufo.columns.str.replace(' ', '_')
# Index(['city', 'colors_reported', 'shape_reported', 'state', 'time'], dtype='object')