I’ll show you how to read a csv file and convert it into a NumPy array in this post. We’ll write NumPy data to a CSV file. The CSV file will then be read and transformed to a Numpy array. I’ll show you how to read a CSV file using both numpy.loadtxt()
and numpy.genfromtxt()
methods.
CSV is a plain-text file that enables data editing and importation into spreadsheets and databases easier. The CSV files can be directly manipulated by Python like a text file or string.
The term Numpy comes from the phrase “Numerical Python”. It is a Python package that performs n-dimensional array operations.
You can also checkout other python tutorials:
- Reading Excel Using Python Pandas
- Read and Write CSV Data Using Python
- Import CSV File into MongoDB using Python
- Read CSV File Using read_csv() method
- Read CSV file Using Numpy
Read CSV file Using Numpy
Let’s read CSV file using a method and converted them into NumPy array.
Using numpy.loadtxt()
The numpy.loadtxt()
is used to load data from a text file in python. In the text file, each row must contain an equal number of values.
Syntax:numpy.loadtxt(fname, …)
The parameters are :
- fname : The file name.
- dtype : Data-type of the resulting array . The default data
type(dtype)
parameter fornumpy.loadtxt( )
is float. - delimiter : The string used to separate values.The default is any whitespace.
- converters : A dictionary mapping column number to a function that will convert that column to a float.
- skiprows : Skip the first skiprows lines. The default is 0.
import numpy as np data = np.loadtxt("test.csv", dtype=int) #converted to integer data type print(data)
Using numpy.genfromtxt()
The Numpy genfromtxt() function
is used to load the data from the text files, with missing values handled as specified.
Syntax:numpy.genfromtxt(fname, filling_values=None, …)
The parameters are :
- name: It is the file
- dtype: It is the data type of the resulting array.
- comment: optional parameter and use for comment.
- delimiter: optional parameter and used to separate values.
- skip_header: optional parameter and use to skip lines from the beginning of the file.
- missing_values: optional parameter and use to set of strings corresponding to missing data.
- filling_values: optional parameter and use to set of values to be used as default when the data are missing.
To load a CSV file, let’s write a Python script. We’ll make a Numpy array and write it to a CSV file, then read that CSV file using numpy genfromtxt() method.
import numpy as np # Let's creat a numpy array nparray = np.array([[1, 3, 5],[2, 4, 6],[1, 5, 6]]) # Saving the array np.savetxt("test.csv", nparray, delimiter=",") # Reading the csv into an array numarray = np.genfromtxt("test.csv", delimiter=",") print(numarray)