The Wayback Machine - https://web.archive.org/web/20241225235426/https://www.geeksforgeeks.org/creating-a-dataframe-using-csv-files/
Open In App

Creating a dataframe using CSV files

Last Updated : 23 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

CSV files are the “comma-separated values”, these values are separated by commas, this file can be viewed like 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 get in CSV file format. Creating a pandas data frame using CSV files can be achieved in multiple ways.

Method #1: Using read_csv() method: read_csv() is an important pandas function to read csv files and do operations on it.
Example: 
 

Python3




# Python program to illustrate
# creating a data frame using CSV files
  
# import pandas module
import pandas as pd
  
# creating a data frame
df = pd.read_csv("CardioGoodFitness.csv")
print(df.head())


Output:
 

csv-to-df-pandas

Method #2: Using read_table() method: read_table() is another important pandas function to read csv files and create data frame from it.
Example: 
 

Python3




# Python program to illustrate
# creating a data frame using CSV files
  
# import pandas module
import pandas as pd
  
# creating a data frame
df = pd.read_table("CardioGoodFitness.csv", delimiter =", ")
print(df.head())


Output:
 

csv-to-df-pandas

Method #3: Using the csv module: One can directly import the csv files using the csv module and then create a data frame using that csv file.
Example: 
 

Python3




# Python program to illustrate
# creating a data frame using CSV files
  
# import pandas module
import pandas as pd
# import csv module
import csv
  
with open("CardioGoodFitness.csv") as csv_file:
    # read the csv file
    csv_reader = csv.reader(csv_file)
  
    # now we can use this csv files into the pandas
    df = pd.DataFrame([csv_reader], index = None)
  
# iterating values of first column 
for val in list(df[1]):
    print(val)


Output: 
 

['TM195', '18', 'Male', '14', 'Single', '3', '4', '29562', '112']

 



Next Article

Similar Reads

Practice Tags :
three90RightbarBannerImg