Python - Name columns explicitly in a Pandas DataFrame



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
Updated on: 2021-10-01T12:26:53+05:30

309 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements