Load CSV file with Numpy

This recipe includes the following topics:

  • Load a csv file using Numpy
  • Load an external csv file(github) using urlopen


# import modules
from numpy import loadtxt

filename = 'pima-indians-diabetes.data.csv'

# open file in read mode
f = open(filename, 'r')

# load file with comma delimiter
pimaArr = loadtxt(f, delimiter=',')

# display row, count size
print(pimaArr.shape)

# display first row
print(pimaArr[0])
(768, 9)

array([  6.   , 148.   ,  72.   ,  35.   ,   0.   ,  33.6  ,   0.627,
        50.   ,   1.   ])

# import modules
from numpy import loadtxt
from urllib.request import urlopen

fileGitURL = 'https://raw.githubusercontent.com/andrewgurung/data-repository/master/pima-indians-diabetes.data.csv'

# open external file using urlopen
f = urlopen(fileGitURL)

# load file with comma delimiter
pimaArr = loadtxt(f, delimiter=',')

# display row, count size
print(pimaArr.shape)

# display first row
print(pimaArr[0])
(768, 9)

array([  6.   , 148.   ,  72.   ,  35.   ,   0.   ,  33.6  ,   0.627,
        50.   ,   1.   ])

Leave a Reply

Your email address will not be published. Required fields are marked *