Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Data preprocessing
  • Data Manipulation
  • Data Analysis using Pandas
  • EDA
  • Pandas Exercise
  • Pandas AI
  • Numpy
  • Matplotlib
  • Plotly
  • Data Analysis
  • Machine Learning
  • Data science
Open In App
Next Article:
How to import an excel file into Python using Pandas?
Next article icon

Different ways to import csv file in Pandas

Last Updated : 11 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

CSV files are the “comma separated values”, these values are separated by commas, this file can be viewed as an Excel file. In Python, Pandas is the most important library coming to data science. We need to deal with huge datasets while analyzing the data, which usually can be in CSV file format. Let’s see the different ways to import csv files in Pandas.

Ways to Import CSV File in Pandas

There are various ways to import CSV files in Pandas, here we are discussing some generally used methods for importing CSV files in pandas.

  • Using read_csv() Method
  • Using csv Module.
  • Using numpy Module

Import a CSV File into Python using Pandas

In this method the below code uses the panda’s library to read an NBA-related CSV file from a given URL, creating a DataFrame named `df`. It then prints the first 10 rows of the DataFrame to provide a brief overview of the dataset.

Python3




# importing pandas module 
import pandas as pd 
     
# making data frame 
df = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") 
   
df.head(10)
 
 

Output:

Providing file_path

In this example the below code uses the pandas library to read a CSV file (“C:\Gfg\datasets\nba.csv”) into a DataFrame and then prints the first five rows of the DataFrame.

Python3




# import pandas as pd
import pandas as pd
  
# Takes the file's folder
filepath = r"C:\Gfg\datasets\nba.csv";
  
# read the CSV file
df = pd.read_csv(filepath)
  
# print the first five rows
print(df.head())
 
 

Output:

Import CSV file in Pandas using csv module.

One can directly import the csv files using csv module. In this code example the below code reads a CSV file (“nba.csv”) into a Pandas DataFrame using Python’s `csv` and `pandas` modules. It then prints the values in the first column of the DataFrame. A correction is needed in the DataFrame creation line for accurate functionality.

Python3




# import the module csv
import csv
import pandas as pd
  
# open the csv file
with open(r"C:\Users\Admin\Downloads\nba.csv") as csv_file:
     
    # read the csv file
    csv_reader = csv.reader(csv_file, delimiter=',')
      
    # now we can use this csv files into the pandas
    df = pd.DataFrame([csv_reader], index=None)
    df.head()
     
# iterating values of first column
for val in list(df[1]):
    print(val)
 
 

Output:

Loading CSV Data into a NumPy Array

Way to import a CSV file in Python is by using the numpy library. The numpy library provides the genfromtxt() function, which can be used to read data from a CSV file and create a NumPy array.

Example : Replace 'path/to/your/file.csv' with the actual path to your CSV file. The delimiter=',' parameter indicates that the values in the CSV file are separated by commas. This method is useful when you want to work with numerical data and leverage the capabilities of the NumPy library.

Python3




import numpy as np
 
# Specify the path to the CSV file
csv_file_path = 'path/to/your/file.csv'
 
# Use genfromtxt to read the CSV file into a NumPy array
data_array = np.genfromtxt(csv_file_path, delimiter=',')
 
# Now, data_array contains the data from the CSV file
print(data_array)
 
 

Output :

[[1.  2.  3.]  [4.  5.  6.]  [7.  8.  9.]] 

This is a hypothetical example assuming the CSV file contains a 3×3 matrix of numerical values separated by commas.



Next Article
How to import an excel file into Python using Pandas?
author
soundarajthevan
Improve
Article Tags :
  • Python
  • Python pandas-basics
  • Python-pandas
Practice Tags :
  • python

Similar Reads

  • Export Pandas dataframe to a CSV file
    When working on a Data Science project one of the key tasks is data management which includes data collection, cleaning and storage. Once our data is cleaned and processed it’s essential to save it in a structured format for further analysis or sharing. A CSV (Comma-Separated Values) file is a widel
    3 min read
  • How to import an excel file into Python using Pandas?
    It is not always possible to get the dataset in CSV format. So, Pandas provides us the functions to convert datasets in other formats to the Data frame. An excel file has a '.xlsx' format. Before we get started, we need to install a few libraries. pip install pandas pip install xlrd For importing an
    2 min read
  • How to export Pandas DataFrame to a CSV file?
    Let us see how to export a Pandas DataFrame to a CSV file. We will be using the to_csv() function to save a DataFrame as a CSV file. DataFrame.to_csv() Syntax : to_csv(parameters) Parameters : path_or_buf : File path or object, if None is provided the result is returned as a string. sep : String of
    3 min read
  • Different ways to create Pandas Dataframe
    It is the most commonly used Pandas object. The pd.DataFrame() function is used to create a DataFrame in Pandas. There are several ways to create a Pandas Dataframe in Python. Example: Creating a DataFrame from a Dictionary [GFGTABS] Python import pandas as pd # initialize data of lists. data = {
    7 min read
  • How to delete a CSV file in Python?
    In this article, we are going to delete a CSV file in Python. CSV (Comma-separated values file) is the most commonly used file format to handle tabular data. The data values are separated by, (comma). The first line gives the names of the columns and after the next line the values of each column. Ap
    2 min read
  • How to load a TSV file into a Pandas DataFrame?
    In this article, we will discuss how to load a TSV file into a Pandas Dataframe. The idea is extremely simple we only have to first import all the required libraries and then load the data set by using various methods in Python.  Dataset Used:  data.tsv Using read_csv() to load a TSV file into a Pan
    1 min read
  • How to import and export data using CSV files in PostgreSQL
    In this article, we are going to see how to import and export data using CSV file in PostgreSQL, the data in CSV files can be easily imported and exported using PostgreSQL. To create a CSV file, open any text editor (notepad, vim, atom). Write the column names in the first line. Add row values separ
    3 min read
  • How to Import Data From a CSV File in MySQL?
    Importing data from a CSV (Comma-Separated Values) file into a MySQL database is a common task for data migration and loading purposes. CSV files are widely used for storing and exchanging tabular data. However, we cannot run SQL queries on such CSV data so we must convert it to structured tables. I
    10 min read
  • How to check if a csv file is empty in pandas
    Reading CSV (Comma-Separated Values) files is a common step in working with data, but what if the CSV file is empty? Python script errors and unusual behavior can result from trying to read an empty file. In this article, we'll look at methods for determining whether a CSV file is empty before attem
    4 min read
  • Loading Different Data Files in Python
    We are given different Data files and our task is to load all of them using Python. In this article, we will discuss how to load different data files in Python. Loading Different Data Files in PythonBelow, are the example of Loading Different Data Files in Python: Loading Plain Text Files Loading Im
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences