Python - Change column names and row indexes in Pandas DataFrame

PythonServer Side ProgrammingProgrammingPandas

Pandas is a python library offering many features for data analysis which is not available in python standard library. One such feature is the use of Data Frames. They are rectangular grids representing columns and rows. While creating a Data frame, we decide on the names of the columns and refer them in subsequent data manipulation. But there may be a situation when we need to change the name of the columns after the data frame has been created. In this article, we will see how to achieve that.

Using rename()

This is the most preferred method as we can change both the column and row index using this method. We just pass in the old and new values as a dictionary of key-value pairs to this method and save the data frame with a new name.

Example

 Live Demo

import pandas as pd

df = pd.DataFrame({
   'ColumnA': [23, 92, 32],
   'ColumnB': [54, 76, 43],
   'ColumnC': [16, 45, 10]
},
index=['10-20', '20-30', '30-40'])

df_renamed = df.rename(columns={'ColumnA': 'Col1', 'ColumnB': 'Col2', 'ColumnC': 'Col3'},
index={'10-20': '1', '20-30': '2', '30-40': '3'})
print(df)
print("\n",df_renamed)

Output

Running the above code gives us the following result:

            ColumnA    ColumnB    ColumnC
10-20            23         54         16
20-30            92         76         45
30-40            32         43         10

           Col1      Col2        Col3
1          23         54          16
2          92         76          45
3          32         43          10

Using df.columns

The df.columns can be assigned new column names directly. When the Data frame is used again, the new column names are referred.

Example

 Live Demo

import pandas as pd

df = pd.DataFrame({
   'ColumnA': [23, 92, 32],
   'ColumnB': [54, 76, 43],
   'ColumnC': [16, 45, 10]
},
index=['10-20', '20-30', '30-40'])

df.columns=["Length","Breadth","Depth"]
print(df)

Output

Running the above code gives us the following result:

          Length      Breadth Depth
10-20 23 54 16
20-30 92 76 45
30-40 32 43 10

By Adding Prefix

Pandas dataframe provides methods for adding prefix and suffix to the column names. We simply use this method to add the desired prefix which gets appended to each column names.

Example

 Live Demo

import pandas as pd

df = pd.DataFrame({
   'ColA': [23, 92, 32],
   'ColB': [54, 76, 43],
   'ColC': [16, 45, 10]
},
index=['10-20', '20-30', '30-40'])

print(df.add_prefix('Jan-'))

Output

Running the above code gives us the following result:

         Jan-ColA    Jan-ColB    Jan-ColC
10-20          23          54          16
20-30          92          76          45
30-40          32          43          10
raja
Published on 02-Jan-2020 14:48:05
Advertisements