How to rename columns in Pandas

You can rename columns in Pandas with any of the following methods. I highly recommend you This book to learn Python. You will see 2 methods to rename columns.

Step 1: Install Pandas Library

Install the Pandas library using this code, if it is not installed.

pip install pandas

Method 1

In the first method, I will use the df.columns method to rename the columns of Pandas DataFrame.

# Import the Pandas library as pd
import pandas as pd

# Initialize a NumPy Array
a = np.array([[95, 90, 75], [19, 17, 13], [75, 52, 89]])

# Create DataFrame
df = pd.DataFrame(a, columns=['A', 'B', 'C'])

# Display the Original DataFrame
print(df)

# Rename Columns
df.columns = ['new_A', 'new_B', 'new_C']

# Display the DataFrame
print(df)

Output:

    A   B   C
0  95  90  75
1  19  17  13
2  75  52  89
   new_A  new_B  new_C
0     95     90     75
1     19     17     13
2     75     52     89

Method 2

In this method, I will use the df.rename() method to change the name of columns.

# Import the Pandas library as pd
import pandas as pd

# Initialize a NumPy Array
a = np.array([[95, 90, 75], [19, 17, 13], [75, 52, 89]])

# Create DataFrame
df = pd.DataFrame(a, columns=['A', 'B', 'C'])

# Display the Original DataFrame
print(df)

# Rename Two Columns
df.rename(columns= {'A': 'new_A', 'B': 'new_B'} , inplace=True)

# Display the DataFrame
print(df)

Output:

    A   B   C
0  95  90  75
1  19  17  13
2  75  52  89
   new_A  new_B   C
0     95     90  75
1     19     17  13
2     75     52  89

Example: Rename CSV Data in Pandas

# Import the Pandas library as pd
import pandas as pd

# Read the CSV file as Pandas DataFrame
df = pd.read_csv("house_price.csv")

# Display the Original DataFrame
print(df)
   Area  Rooms  House_Age  Price
0  5000      5          5  75000
1  4000      4          5  65000
2  3000      3          1  60000
3  2000      3          1  58000
4  1500      2          1  50000
5  7000      5          5  90000
6  6000      5          3  85000
7  6500      4          7  80000
8  8000      5         15  95000

Now, I want to rename two columns.

# Rename Two Columns
df.rename(columns= {'Rooms': 'No. of Rooms', 'House_Age': 'Duration'} , inplace=True)

# Display the DataFrame
print(df)
   Area  No. of Rooms  Duration  Price
0  5000             5         5  75000
1  4000             4         5  65000
2  3000             3         1  60000
3  2000             3         1  58000
4  1500             2         1  50000
5  7000             5         5  90000
6  6000             5         3  85000
7  6500             4         7  80000
8  8000             5        15  95000

Free Learning Resources

Leave a Comment

Your email address will not be published.