We can use the numpy.genfromtxt() function to read data from a text file. In this article, we will read a CSV file using the numpy.genfromtxt() function. The function will return an ndarray that contains the records from the CSV file.
Please note that a CSV or Comma Separated Values file is a type of text file in which different values are separated using commas. A CSV file can contain several records with one record in each line. Each record contains various fields. And these fields are separated using commas.
In this example, we will read a CSV file named “iris.csv”. The CSV file contains 150 records. Each record contains five fields. They are sepal length, sepal width, petal length, petal width and species of flowers. Among these fields the first four fields contain floating point numbers and the last field contains strings.
We can use the following Python code to read the CSV file.
import numpy data = numpy.genfromtxt("iris.csv", delimiter=",", dtype={'names': ('sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species'), 'formats': (numpy.float32, numpy.float32, numpy.float32, numpy.float32, '|S15')}, skip_header=1) print(data.shape) print(data)
Please note that the numpy.genfromtxt() function can take several arguments. The first argument is the name of the file, which is “iris.csv” in our case. In a CSV file, the fields are separated using commas. So, the delimiter is “,” here.
Please note the dtype argument. By default, numpy.genfromtxt() function can read floating point numbers. But, our CSV file …






0 Comments