To name columns explicitly, use the names parameter of the read_csv() method. Let’s say the following is our CSV file without headers opened in Microsoft Excel −
Let us load data from CSV file and with that add header columns using the names parameter −
pd.read_csv("C:\\Users\\amit_\\Desktop\\TeamData.csv",names=['Team', 'Rank_Points', 'Year'])
Example
Following is the complete code −
import pandas as pd # Load data from a CSV file into a Pandas DataFrame dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\TeamData.csv") print("Reading the CSV file without headers...\n", dataFrame) # adding headers dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\TeamData.csv",names=['Team', 'Rank_Points', 'Year']) # reading updated CSV print("\nReading the CSV file after updating headers...\n", dataFrame)
Output
This will produce the following output −
Reading the CSV file without headers... Australia 2500 2021 0 Bangladesh 1000 2021 1 England 2000 2021 2 India 3000 2021 3 Srilanka 1500 2021 Reading the CSV file after updating headers... Team Rank_Points Year 0 Australia 2500 2021 1 Bangladesh 1000 2021 2 England 2000 2021 3 India 3000 2021 4 Srilanka 1500 2021