Recipe: How to import a CSV file in Python?
MACHINE LEARNING RECIPES

How to import a CSV file in Python?

This recipe helps you import a CSV file in Python
In [1]:
## How to import a CSV file in Python
def Snippet_171():
    print()
    print(format('How to import a CSV file in Python','*^82'))

    import warnings
    warnings.filterwarnings("ignore")

    # load libraries
    import csv
    import numpy
    import pandas

    # Load CSV (using python)
    filename = 'pima.indians.diabetes.data.csv'
    raw_data = open(filename, 'rt')
    reader = csv.reader(raw_data, delimiter=',', quoting=csv.QUOTE_NONE)
    x = list(reader)
    data = numpy.array(x).astype('float')
    print(data.shape)

    # Load CSV (using numpy)
    filename = 'pima.indians.diabetes.data.csv'
    raw_data = open(filename, 'rt')
    data = numpy.loadtxt(raw_data, delimiter=",")
    print(data.shape)

    # Load CSV (using Pandas)
    filename = 'pima.indians.diabetes.data.csv'
    names = ['preg', 'plas', 'pres', 'skin', 'test',
             'mass', 'pedi', 'age', 'class']
    data = pandas.read_csv(filename, names=names)
    print(data.shape)

Snippet_171()
************************How to import a CSV file in Python************************
(768, 9)
(768, 9)
(768, 9)


Stuck at work?
Can't find the recipe you are looking for. Let us know and we will find an expert to create the recipe for you. Click here
Companies using this Recipe