how to rename a column in pandas dataframe in python

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

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

Here, df refers to the dataframe object, old_column_name is the current name of the column that you want to rename, and new_column_name is the new name that you want to give to the column.

By setting inplace=True, the dataframe will be modified in place, without creating a new dataframe object. If you omit this parameter or set it to False, a new dataframe with the renamed column will be returned.

Here's an example:

main.py
# Import pandas
import pandas as pd

# Create a dataframe
data = {'Name': ['John', 'Emma', 'Ryan'],
        'Age': [25, 28, 30],
        'City': ['New York', 'San Francisco', 'Seattle']}
df = pd.DataFrame(data)

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

# Check the updated dataframe
print(df)
352 chars
15 lines

Output:

main.py
  First Name  Age           City
0       John   25       New York
1       Emma   28  San Francisco
2       Ryan   30        Seattle
132 chars
5 lines

In the above example, we renamed the 'Name' column to 'First Name' using the rename() function.

Remember to assign the updated dataframe back to df (or a different variable) if you want to keep the changes.

related categories

gistlibby LogSnag