Pandas DataFrame: Rename columns of a given DataFrame
Pandas: DataFrame Exercise-23 with Solution
Write a Pandas program to rename columns of a given DataFrame.
Sample data:
Original DataFrame
col1 col2 col3
0 1 4 7
1 2 5 8
2 3 6 9
New DataFrame after renaming columns:
Column1 Column2 Column3
0 1 4 7
1 2 5 8
2 3 6 9
Sample Solution :
Python Code :
import pandas as pd
d = {'col1': [1, 2, 3], 'col2': [4, 5, 6], 'col3': [7, 8, 9]}
df = pd.DataFrame(data=d)
print("Original DataFrame")
print(df)
df.columns = ['Column1', 'Column2', 'Column3']
df = df.rename(columns={'col1': 'Column1', 'col2': 'Column2', 'col3': 'Column3'})
print("New DataFrame after renaming columns:")
print(df)
Sample Output:
Original DataFrame col1 col2 col3 0 1 4 7 1 2 5 8 2 3 6 9 New DataFrame after renaming columns: Column1 Column2 Column3 0 1 4 7 1 2 5 8 2 3 6 9
Explanation:
The above code first creates a Pandas DataFrame 'df' from a dictionary 'd' with 3 columns 'col1', 'col2', and 'col3'.
df = df.rename(columns={'col1': 'Column1', 'col2': 'Column2', 'col3': 'Column3'}): This line changes the column names of the DataFrame using two different methods. First, it sets the column names using the .columns attribute, and then it renames the columns using the .rename() method with a dictionary mapping the old column names to the new column names.
Finally, it prints the DataFrame with the new column names using print() function.
Python-Pandas Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Pandas program to get list from DataFrame column headers.
Next: Write a Pandas program to select rows from a given DataFrame based on values in some columns.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/pandas/python-pandas-data-frame-exercise-23.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics