There are 2 methods of changing the column names of Pandas Dataframes. The following shows the basic Python code syntax for changing column names of Pandas Dataframes.
Method 1:
df.rename(columns={‘old_name_1′:’new_name_1’, ‘old_name_2′:’new_name_2’}, inplace=True)
Method 2:
df = df.rename({‘old_name_1′:’new_name_1’, ‘old_name_2′:’new_name_2’}, axis=1)
Example 1 of changing column names of Pandas DataFrames (Method 1)
The following is the first example of changing column names of Pandas DataFrames.
import pandas as pd
# Create a sample DataFrame
df = pd.DataFrame({'col1': [3, 5], 'col2': [13, 14]})
# print out the old dataframe
print("Dataframe with old names:\n",df)
# Change the column names
df.rename(columns={'col1': 'column1', 'col2': 'column2'}, inplace=True)
# print out the new dataframe
print("Dataframe with new names:\n",df)
Dataframe with old names: col1 col2 0 3 13 1 5 14 Dataframe with new names: column1 column2 0 3 13 1 5 14
Example 2 of changing column names of Pandas DataFrames (Method 2)
The following is the second example of changing the column names of Pandas DataFrames.
import pandas as pd
# Create a sample DataFrame
df = pd.DataFrame({'col1': [3, 5], 'col2': [13, 14]})
# print out the old dataframe
print("Dataframe with old names:\n",df)
# Change the column names
df=df.rename({'col1': 'column1', 'col2': 'column2'}, axis=1)
# print out the new dataframe
print("Dataframe with new names:\n",df)
Dataframe with old names: col1 col2 0 3 13 1 5 14 Dataframe with new names: column1 column2 0 3 13 1 5 14