How to rename column names in a Pandas DataFrame?

PandasServer Side ProgrammingProgramming

To rename columns in a Pandas DataFrame, we can override df.columns with the new column names.

Steps

  • Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.

  • Print the input DataFrame.

  • Override the columns with new list of column names.

  • Print the DataFrame again with the renamed column names.

Example

 Live Demo

import pandas as pd

df = pd.DataFrame(
   {
      "x": [5, 2, 1, 9],
      "y": [4, 1, 5, 10],
      "z": [4, 1, 5, 0]
   }
)

print("Input DataFrame is:\n", df)

df.columns = ["a", "b", "c"]

print("After renaming, DataFrame is:\n", df)

Output

Input DataFrame is:
   x  y  z
0  5  4  4
1  2  1  1
2  1  5  5
3  9 10  0
After renaming, DataFrame is:
   a  b  c
0  5  4  4
1  2  1  1
2  1  5  5
3  9 10  0
raja
Published on 30-Aug-2021 09:14:47
Advertisements