rename a pandas df columns in python

To rename the columns of a pandas DataFrame in Python, you can use the rename() method. Here is an example:

main.py
import pandas as pd

# Create a sample DataFrame
data = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}
df = pd.DataFrame(data)

# Rename the columns
new_columns = {'A': 'Column 1', 'B': 'Column 2', 'C': 'Column 3'}
df = df.rename(columns=new_columns)

# Display the updated DataFrame
print(df)
296 chars
13 lines

This will output the DataFrame with the new column names:

main.py
   Column 1  Column 2  Column 3
0         1         4         7
1         2         5         8
2         3         6         9
128 chars
5 lines

In this example, we define a dictionary new_columns where the keys are the original column names and the values are the desired new column names. The rename() method is then used to update the column names of the DataFrame.

Note that the rename() method returns a new DataFrame with the updated column names, so we assign it back to df to keep the changes.

Make sure to import the pandas library before using it.

related categories

gistlibby LogSnag