In Python programming, you sometimes need to add column names to an already existing DataFrame. This is especially important when you are dealing with large datasets where you want to make column references easier.
These renamed columns can enhance code readability and output visualizations. Fortunately, Python’s Pandas library makes this task considerably easier. This tutorial will guide you on how you can add names to your DataFrame using this library.
We will use the following data for this tutorial:
5 3 8 2 6 7 1 8 2 4 7 6 3 2 0
Step 1: Import Necessary Libraries
To start, we need to import the Pandas library. If you haven’t installed it before, you can do this by using the pip install pandas command in your command prompt or terminal. Here is how to import:
1 |
import pandas as pd |
Step 2: Create a DataFrame
Let’s assume we have a DataFrame that has no column names or column names that we want to change. We can create our DataFrame from the data above using the DataFrame constructor as shown below:
1 2 3 |
data = [[5,3,8], [2,6,7], [1,8,2], [4,7,6], [3,2,0]] df = pd.DataFrame(data) print(df) |
You’ll see the DataFrame printed without any column names.
Step 3: Adding Column Names
Adding or Changing column names in a DataFrame in Pandas is straightforward. We can do this using the columns attribute of the DataFrame. Here is how:
1 2 |
df.columns = ['Column1', 'Column2', 'Column3'] print(df) |
You should now be able to see the new column names when you print your DataFrame.
The complete code:
1 2 3 4 5 6 7 8 9 |
import pandas as pd # Creating DataFrame data = [[5,3,8], [2,6,7], [1,8,2], [4,7,6], [3,2,0]] df = pd.DataFrame(data) # Adding Column Names df.columns = ['Column1', 'Column2', 'Column3'] print(df) |
Column1 Column2 Column3 0 5 3 8 1 2 6 7 2 1 8 2 3 4 7 6 4 3 2 0
Conclusion
Adding column names to an existing DataFrame in Python is quite easy and can be accomplished using a few lines of code.
It is a handy tool when you are dealing with large datasets and you want to increase the readability of your code and output visualizations.
Remember this tutorial next time you need to add or change DataFrame column names in your Python work.