Pandas, How to rename a column in a DataFrame.

Syntax:


df = df.rename(index=str, columns={"OLDNAME": "NEWNAME", "OLDNAME1": "NEWNAME1"})

A column of a DataFrame is renamed using the rename method. The column is referenced by index or by name.

Example:

This example creates a DataFrame with 4 columns and 5 rows. The column A is renamed to NEW_A and the column C is renamed to the value NEW_c. The output of the process is written in the output.

import pandas as pd 
import numpy as np 

df = pd.DataFrame(np.arange(20).reshape(5,4),
                   columns=['A', 'B', 'C', 'D'])
print( df )

# Drop column B and D
df = df.rename(index=str, columns={"A": "NEW_A", "C": "NEW_c"})

print()

print( df )

The output will be:

    A   B   C   D
0   0   1   2   3
1   4   5   6   7
2   8   9  10  11
3  12  13  14  15
4  16  17  18  19

   NEW_A   B  NEW_c   D
0      0   1      2   3
1      4   5      6   7
2      8   9     10  11
3     12  13     14  15
4     16  17     18  19

References:

Pandas DataFrame rename

Recent Comments