rename a column in pandas dataframe in python

To rename a column in a pandas DataFrame in Python, you can use the rename() method. Here's the syntax:

main.py
df.rename(columns={'old_column_name': 'new_column_name'}, inplace=True)
72 chars
2 lines

In this syntax, df is the DataFrame you want to modify, old_column_name is the name of the column you want to rename, and new_column_name is the new name you want to assign to the column.

The inplace=True parameter ensures that the modification is made directly to the DataFrame, without creating a new copy.

Here's an example:

main.py
import pandas as pd

# Create a DataFrame
data = {'Name': ['John', 'Emma', 'Ryan'],
        'Age': [25, 28, 31]}
df = pd.DataFrame(data)

# Rename the 'Age' column to 'Years'
df.rename(columns={'Age': 'Years'}, inplace=True)

print(df)
236 chars
12 lines

Output:

main.py
   Name  Years
0  John     25
1  Emma     28
2  Ryan     31
60 chars
5 lines

In this example, the column 'Age' is renamed to 'Years' using the rename() method.

Remember to assign the modified DataFrame back to the original variable or a new variable if you intend to use it further.

related categories

gistlibby LogSnag