Load CSV file into pandas Data Frame

Previous
Next

CSV file:

  • CSV(comma separated values) file.
  • Using text files, we can store only textual raw data.
  • Using CSV files, we can store information in tabular format like excel sheets
data.csv:
101,amar,50000
102,annie,40000
103,hareen,60000

Reading from csv file:

  • ‘csv’ is a pre-defined module
  • ‘csv’ module contains reader() funtion to construct data object.
  • We can access the information from data object using iterators(loops)
import csv
class ReadCSV:
    file = None
    def main():
        try :
            ReadCSV.file = open("./data.csv", "r")
            print("File opened...")

            table = csv.reader(ReadCSV.file)
            print("Records are :")
            for record in table:
                print(record)

        except Exception as e:
            print("Exception :",e)

        finally:
            if ReadCSV.file != None:
                ReadCSV.file.close()
                print("File closed...")
        return

ReadCSV.main()

Load CSV into DataFrame:

It’s quite simple to load data from various file formats into a DataFrame. In the following examples we’ll keep using our apples and oranges data, but this time it’s coming from various files.

Using pre-defined function read_csv(), we can load the file into Frame:

import pandas as pd
frame = pd.read_csv(".\data.csv")
print("Data is :")
print(frame)

Output:

Data is:
   eno     ename    esal      address
0   101      Ram    30000   Hyderabad
1   102    Rahim    40000   Bangalore
2   103   Robert    50000     Chennai
Previous
Next

Courses Enquiry Form