numpy.loadtxt() in Python is used load data from a text file, with aim to be a fast reader for simple text files.
Note that each row in the text file must have the same number of values.
Here is myfile.csv file content
5.1,3.5,1.4,0.2,Iris-setosa
4.9,3.0,1.4,0.2,Iris-setosa
5.8,2.7,4.1,1.0,Iris-versicolor
6.2,2.2,4.5,1.5,Iris-versicolor
6.4,3.1,5.5,1.8,Iris-virginica
6.0,3.0,4.8,1.8,Iris-virginica
Load NumPy library
# import numpy library as np
import numpy as np
# numerical data file
filename="myfile.csv"
Load a csv file with NumPy
# load the data with NumPy function loadtxt
data = np.loadtxt(filename, delimiter=",")
Load a csv file with NumPy and skip a row
# use skiprows to skip rows
data = np.loadtxt(filename, delimiter=",", skiprows=1)
Load a csv file with NumPy, skip a row and select columns
# usecols select columns
data = np.loadtxt(filename, delimiter=",", skiprows=1,usecols=[0,1,2])
Note: If you have tab-delimited file, we can specify the delimter to “\t”