How to rename one or multiple columns using python pandas?

There are several ways to change the name of columns in a Python pandas data frame or series.

In your Python script, import the pandas library and read a file. We will read a csv file and rename the columns contained within it.

import pandas as pd

df_csv = pd.read_csv('sample1.csv')

Method 1: Rename the columns or index of a data frame using the rename function. The rename function requires at least one parameter, which is the name of the existing columns to be renamed and the new name for the columns. The other parameter we’ll pass is ‘inplace’, which determines whether to modify the data frame rather than create one. You pass the dictionary of the existing column name and the new column name to a rename function, so you can rename one, multiple, or all column names.

df_csv.rename(columns = {'director_name' : 'director'}, inplace = True)

Method 2: You can add new column names to the data frame directly. The condition here is that you must pass the same number of new column names as you do in your data frame. For example, if your data frame already has four columns, you must pass four new column names.

df_csv.columns = ['director', 'reviews', 'total_duration', 'facebook_likes']