In python, we can use the numpy.loadtxt() function to load data from a text file. In this article, we will look into an example and see how to load data from a CSV file using the numpy.loadtxt() function.
A CSV or Comma Separated Values file is a type of text file in which values are separated using commas. Each line of the text file contains one data record. Each record contains one or more fields. And these fields are separated using commas.
For example, in this article, we will read the iris.csv file. This file contains 150 records. And each record contains 5 fields. They are sepal length, sepal width, petal length, and petal width of flowers and the species of the flower. Please note that sepal length, sepal width, petal length, and petal width contain floating point numbers. And the species field contains strings.
The numpy.loadtxt() function can read the iris.csv file and return an ndarray. We can use the following Python code for that purpose:
import numpy data = numpy.loadtxt("iris.csv", delimiter=",", skiprows=1, dtype={'names': ('sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species'), 'formats': (numpy.float32, numpy.float32, numpy.float32, numpy.float32, '|S15')}) print(data.shape) print(data)
The first argument of the numpy.loadtxt() function is the filename. As different fields are separated using commas in a CSV file, we are using “,” as a delimiter. The first line of the CSV file contains the names of the fields. And lines 2 to 151 contain the values of the corresponding fields. So, we will skip the first row while reading the CSV file.
Please note the dtype argument of the numpy.loadtxt() function. It contains a dictionary. Here, “names” indicates the names of …






0 Comments