Different ways to import csv file in Pandas

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.

Let’s see the different ways to import csv file in Pandas.

Method #1: Using read_csv() method.



filter_none

edit
close

play_arrow

link
brightness_4
code

# importing pandas module  
import pandas as pd  
      
# making data frame  
    
df.head(10

chevron_right


Output:

 
Providing file_path.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

 
Method #2: Using csv module.

One can directly import the csv files using csv module.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.