reanme columns of a dataframe in python

To rename the columns of a Pandas DataFrame in Python, you can use the rename function. The rename function takes a dictionary as input, where the keys are the original column names, and the values are the new column names. Here's an example:

main.py
import pandas as pd

# create a sample dataframe
data = {
    'col1': [1, 2, 3],
    'col2': [4, 5, 6],
    'col3': [7, 8, 9]
}
df = pd.DataFrame(data)

# rename the columns
df = df.rename(columns={'col1': 'new_col1', 'col2': 'new_col2', 'col3': 'new_col3'})

# print the updated dataframe
print(df)
300 chars
16 lines

This will output:

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

In this example, we created a sample DataFrame with three columns col1, col2, and col3. We then used the rename method to rename the columns to new_col1, new_col2, and new_col3. Finally, we printed the updated DataFrame with the new column names.

gistlibby LogSnag