Change Variable Names of pandas DataFrame in Python (2 Examples)

In this article, I’ll show how to change the names of columns in a pandas DataFrame in the Python programming language.

Setting up the Examples

import pandas as pd                                            # Load pandas library
my_df = pd.DataFrame({"A":range(100, 105),                    # Constructing pandas DataFrame in Python
                      "B":["e", "f", "g", "h", "i"],
                      "C":range(30, 25, - 1),
                      "D":[1, 0, 1, 1, 0]})
print(my_df)                                                  # Displaying pandas DataFrame
#      A  B   C  D
# 0  100  e  30  1
# 1  101  f  29  0
# 2  102  g  28  1
# 3  103  h  27  1
# 4  104  i  26  0

Example 1: Modify Names of Particular Columns of pandas DataFrame in Python

my_df = my_df.rename(columns = {"B": "B_new", "D": "D_new"})  # Rename some variables
print(my_df)                                                  # Displaying updated DataFrame
#      A B_new   C  D_new
# 0  100     e  30      1
# 1  101     f  29      0
# 2  102     g  28      1
# 3  103     h  27      1
# 4  104     i  26      0

Example 2: Modify Names of Each Column of pandas DataFrame in Python

my_df.columns = ["V1", "V2", "V3", "V4"]                      # Rename all variables
print(my_df)                                                  # Displaying updated DataFrame
#     V1 V2  V3  V4
# 0  100  e  30   1
# 1  101  f  29   0
# 2  102  g  28   1
# 3  103  h  27   1
# 4  104  i  26   0

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top