- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements