df.rename()
The df.rename()
method in pandas is used to alter labels of the index (row labels) or columns of a DataFrame. This method provides a flexible way to rename specific rows or columns without changing the entire structure of the DataFrame.
Here's the basic syntax of the rename()
method:
df.rename(mapper=None, index=None, columns=None, axis=None, inplace=False, ...)
mapper
,index
, orcolumns
parameters can be used to specify the changes. Themapper
can be a dictionary or a function that takes a label and returns a new label.index
andcolumns
are alternatives for specifying the mapper that only apply to the index or columns respectively.axis
specifies which axis to target with the mapper. The value can be 0 or 'index' to target the index (rows), and 1 or 'columns' to target the columns.- If
inplace=True
, the renaming will modify the DataFrame in place, rather than returning a new DataFrame.
Here are some examples of how to use df.rename()
:
Renaming columns using a dictionary:
import pandas as pd
# Sample DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
# Rename columns A to X and B to Y
df_renamed = df.rename(columns={'A': 'X', 'B': 'Y'})
Renaming index using a function:
# Rename index using a lambda function to add 'row_' prefix
df_renamed = df.rename(index=lambda x: 'row_' + str(x))
Renaming while modifying the DataFrame in place:
# Rename in place
df.rename(columns={'A': 'X', 'B': 'Y'}, inplace=True)
The rename()
method is very useful when you need to rename certain columns or rows for better readability or to conform with certain naming conventions without altering the data within the DataFrame.