Load data from a text file using NumPy loadtxt()

Hi guys, Today we will learn about how to load a text file using NumPy loadtxt() in Python with the help of some examples. So basically, the loadtxt() method of the NumPy library is used to load data from a text file. It returns an n-dimensional array(also called a NumPy array)  which contains the data read from the text file.

How to load data from a text file using NumPy loadtxt() in Python

The text file should contain the same number of values in each row to be read by the loadtxt() method.

Syntax of loadtxt()

numpy.loadtxt(fname, dtype=<class ‘float’> , comments= ‘#’ , delimiter= None, converters= None , skiprows= 0 , usecols= None , unpack= False , ndmin= 0, encoding= ‘bytes’, max_rows=None )

Parameters of numpy.loadtxt()

  1. fname: Represents a file or filename to be read.
  2. dtype: This parameter depicts the data type of the resulting array. Default: float
  3. delimiter: It is the set of characters used to separate values. Default: Whitespace
  4. comments: Characters used to distinguish the start of the comment. Default:”#”
  5. converters: Dictionary used for matching column index to a function that converts a column to a float value. Default: None
  6. skiprows: Skips the first specified number of lines, including comments. Default:0
  7. usecols: Parameter states which column to read, with 0 being first. Default: None
  8. unpack: Boolean value. If it is true, it returns the result individually as separate arays. Default: False
  9. ndmin: The returned array has at least n dimensions. Default: 0
  10. encoding: Parameter used for encoding and later decoding the input file. Default: ‘bytes’.
  11. max_rows: This parameter reads the max_rows lines of content after skiprows lines. Default: read all the lines

Example 1:

import numpy as np

from io import StringIo
a=StringIO("11  12  \n  13  14")


[[11.  12.]
[13.  14.]]

Example 2:

import numpy as np
from io import StringIo
obj=StringIo("11  , 22, 33\n 44,  55,  66")
a, b, c=np.loadtxt(obj, delimiter=',',usecols=(0,1,2), unpack= True)
print("a:" ,a)
print("b:" ,b)
print("c:" ,c)


a:     [11.     44.]
b:     [22.    55.]
c:     [33.    66.]

Also, see:

Extracting Text from a Pdf file in Python

Leave a Reply

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