numpy.loadtxt() in Python

The numpy module of Python provides a function to load data from a text file. The numpy module provides loadtxt() function to be a fast reader for simple text files.

Note
Note: In the text file, each row must have the same number of values.

Syntax

snippet
numpy.loadtxt(fname, dtype=<type 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)

Parameters

These are the following parameter in numpy.loadtxt() function:

fname: file, str, or pathlib.Path

This parameter defines the file, filename, or generator to read. Firstly, we will decompose the file, if the filename extension is .gz and .bz2. After that the generators will return byte strings for Python 3k.

dtype: data-type(optional)

This parameter defines the data type for the resulting array, and by default, the data type will be the float. The resulting array will be 1-dimensional when it is a structured data-type. Each row is interpreted as an array element, and the number of columns used must match with the number of fields in the data-type.

comments: str or sequence(optional)

This parameter defines the characters or list of characters used for indicating the start of the comment. By default, it will be '#'.

delimiter: str(optional)

This parameter defines the string used for separating values. By default, it will be any whitespace.

converters: dict(optional)

This parameter defines a dictionary mapping column number to a function that will convert the mapped column to the float. When column() is a date string then converters={0:datestr2num}. This parameter is also used to provide a default value for missing data as converters= {3: lambda s: float(s.strip() or 0)}.

skiprows: int(optional)

This parameter is used to skip the first 'skiprows', and by default, it will be 0.

usecols: int or sequence(optional)

This parameter defines the columns to read, with 0 being the first. For example, usecols=(0, 3, 5) will extract the 1st, 4th, and 5th column. By default, its value is None, which results in all columns being read. In the new version, we can use an integer instead of a tuple if we want to read a single column.

unpack: bool(optional)

If this parameter is set to true, then the returned array is transposed, so that arguments may be unpacked using x, y, z =loadtxt(...). The arrays are returned for each field when using it with the structured data-type. By default, it will be set to False.

ndim: int(optional)

The returned array will have 'ndmin' dimensions. Otherwise, it will squeeze the mono-dimensional axis. Legal values: 0 (default), 1 or 2.

Returns: out(ndarray)

It reads data from the text file in the form of a ndarray.

Example 1:

snippet
import numpy as np
from io import StringIO
c = StringIO(u"0 1\n2 3")
c
np.loadtxt(c)

Output:

Output
<_io.StringIO object at 0x000000000A4C3E48> array([[0., 1.], [2., 3.]])

In the above code

  • We have imported numpy with alias name np.
  • We have also imported StringIO from io.
  • We have declared the variable 'c' and assigned the returned value of the StringIO() function.
  • We have passed the unicode data in the function.
  • Lastly, we tried to print the return value of np.loadtxt() in which we passed the file or filename.

In the output, it shows the content of the file in the form of ndarray.

Example 2:

snippet
import numpy as np
from io import StringIO
d = StringIO(u"M 21 72\nF 35 58")
np.loadtxt(d, dtype={'names': ('gender', 'age', 'weight'),'formats': ('S1', 'i4', 'f4')})

Output:

Output
array([('M', 21, 72.), ('F', 35, 58.)], dtype=[('gender', 'S1'), ('age', '<i4'), ('weight', '<f4')])

Example 3:

snippet
import numpy as np
from io import StringIO
c = StringIO(u"1,3,2\n3,5,4")
x, y = np.loadtxt(c, delimiter=',', usecols=(0, 2), unpack=True)
x
y

Output:

Output
array([1., 3.]) array([2., 4.])

In the above code

  • We have imported numpy with alias name np.
  • We have also imported StringIO from io.
  • We have declared the variable 'c' and assigned the returned value of the StringIO() function.
  • We have passed the unicode data in the function.
  • Lastly, we tried to print the return value of np.loadtxt in which we passed the file or filename, set delimiter, usecols, and unpack to True.

In the output, it displays the content of the file has been shown in the form of ndarray.

Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +