Creating a dataframe using CSV files

CSV files are the “comma-separated values”, these values are separated by commas, this file can be view like as 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.

Note: Get the csv file used in the below examples from here.

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

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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())

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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())

chevron_right


Output:

csv-to-df-pandas

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

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

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

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Technical Content Engineer at GeeksForGeeks

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.