pandas
  1. pandas-dataframerename

DataFrame.rename() - ( Pandas DataFrame Basics )

Heading h2

Syntax

DataFrame.rename(mapper=None, index=None, columns=None, axis=None, copy=True, inplace=False, level=None)

Example

import pandas as pd

data = {
  "name": ["John", "Peter", "Sara"],
  "age": [25, 30, 35],
  "city": ["New York", "Paris", "Sydney"]
}
df = pd.DataFrame(data)

df = df.rename(columns={"name": "full_name"})

print(df)

Output

  full_name  age      city
0      John   25  New York
1     Peter   30     Paris
2      Sara   35    Sydney

Explanation

The rename() method in a Pandas DataFrame is used to change the names of one or more columns/indices in a DataFrame. The method accepts various parameters such as mapper, index, columns, axis, etc., that can be used to specify the new name for the columns/indices.

In the example above, we create a DataFrame containing columns for name, age, and city. We then use rename() method to rename the 'name' column to 'full_name' by passing a dictionary containing the old and new column names to the columns parameter.

Use

rename() method in a Pandas DataFrame is used to rename one or more columns/indices in a DataFrame. It can be useful when working with large datasets that may have column/indices names that are unclear or hard to understand.

Important Points

  • rename() method is used to rename columns/indices in a Pandas DataFrame
  • Various parameters such as mapper, index, columns, axis, etc., can be used to specify the new name for the columns/indices.
  • rename() creates a new DataFrame unless the inplace parameter is set to True.

Summary

In conclusion, rename() is a useful method when working with Pandas DataFrames. It allows you to rename one or more columns/indices and can be used to ensure that column/indices names are clear and easy to understand. It is important to remember that unless inplace parameter is set to True, rename() creates a new DataFrame.

Published on: