rename dataframe columns in python

To rename dataframe columns in Python using pandas, you can use the rename method. This method allows you to specify new column names for one or more columns.

Here is an example of how to rename dataframe columns:

main.py
import pandas as pd

# Create a dataframe
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# Rename a single column
df.rename(columns={'A': 'NewA'}, inplace=True)

# Rename multiple columns
df.rename(columns={'A': 'NewA', 'B': 'NewB'}, inplace=True)

# Print the updated dataframe
print(df)
295 chars
14 lines

Output:

main.py
   NewA  NewB
0     1     4
1     2     5
2     3     6
56 chars
5 lines

In the code above, we first create a dataframe with columns 'A' and 'B'. Then, we use the rename method to rename the columns. The columns parameter of the rename method takes a dictionary where the keys are the original column names and the values are the new column names. By setting inplace=True, the renaming is done directly on the dataframe.

Note that if you don't set inplace=True, the rename method will return a new dataframe with the renamed columns, but the original dataframe will remain unchanged.

gistlibby LogSnag