w3resource

NumPy Input and Output: loadtxt() function

numpy.loadtxt() function

The loadtxt() function is used to load data from a text file.

Each row in the text file must have the same number of values.

Syntax:

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

Version: 1.15.0

Parameter:

Name Description Required /
Optional
fname File, filename, or generator to read. If the filename extension is .gz or .bz2, the file is first decompressed.
Note that generators should return byte strings for Python 3k.
file, str, or pathlib.Path
Required
dtype Data-type of the resulting array; default: float. If this is a structured data-type, the resulting array will be 1-dimensional,
and each row will be interpreted as an element of the array. In this case, the number of columns used must match the number of fields in the data-type.
data-type
Optional
comments The characters or list of characters used to indicate the start of a comment; default: ‘#’.
str or sequence
Optional
delimiter The string used to separate values. By default, this is any whitespace.
str
Optional
converters A dictionary mapping column number to a function that will convert that column to a float. E.g., if column 0 is a date string: converters = {0: datestr2num}.
Converters can also be used to provide a default value for missing data (but see also genfromtxt): converters = {3: lambda s: float(s.strip() or 0)}.
Default: None.
dict
Optional
skiprows Skip the first skiprows lines; default: 0.
int
Optional
usecols Which columns to read, with 0 being the first. For example, usecols = (1,4,5) will extract the 2nd, 5th and 6th columns.
The default, None, results in all columns being read.
New in version 1.11.0.
Also when a single column has to be read it is possible to use an integer instead of a tuple.
E.g usecols = 3 reads the fourth column the same way as usecols = (3,)` would.
int or sequence
Optional
unpack If True, the returned array is transposed, so that arguments may be unpacked using x, y, z = loadtxt(...).
When used with a structured data-type, arrays are returned for each field. Default is False.
bool
Optional
ndmin The returned array will have at least ndmin dimensions.
Otherwise mono-dimensional axes will be squeezed. Legal values: 0 (default), 1 or 2.
int
Optional
encoding Encoding used to decode the inputfile. Does not apply to input streams.
The special value ‘bytes’ enables backward compatibility workarounds
that ensures you receive byte arrays as results if possible and passes ‘latin1’ encoded strings to converters.
Override this value to receive unicode arrays and pass strings as input to converters.
If set to None the system default is used. The default value is ‘bytes’.
str
Optional

Returns: out : ndarray

Data read from the text file.

Notes:

This function aims to be a fast reader for simply formatted files.
The genfromtxt function provides more sophisticated handling of, e.g., lines with missing values.

The strings produced by the Python float.hex method can be used as input for floats.

NumPy.loadtxt() method Example-1:

>>> import numpy as np
>>> from io import StringIO   # StringIO behaves like a file object
>>> a = StringIO("0 2\n4 6")
>>> np.loadtxt(a)

Output:

array([[0., 2.],
       [4., 6.]])

NumPy.loadtxt() method Example-2:

>>> import numpy as np
>>> from io import StringIO 
>>> b = StringIO("M 25 78\nF 37 55")
>>> np.loadtxt(b, dtype={'names': ('gender', 'age', 'weight'), 'formats': ('S1', 'i4', 'f4')})

Output:

array([(b'M', 25, 78.), (b'F', 37, 55.)],
      dtype=[('gender', 'S1'), ('age', '<i4'), ('weight', '<f4')])

NumPy.loadtxt() method Example-3:

>>> import numpy as np
>>> from io import StringIO 
>>> a = StringIO("2,0,3\n4,0,5")
>>> x, y = np.loadtxt(a, delimiter=',', usecols=(0, 2), unpack=True)
>>> x

Output:

array([2., 4.])

NumPy.loadtxt() method Example-4:

>>> import numpy as np
>>> from io import StringIO 
>>> a = StringIO("2,0,3\n4,0,5")
>>> x, y = np.loadtxt(a, delimiter=',', usecols=(0, 2), unpack=True)
>>> y

Output:

array([3., 5.])  	   

Python - NumPy Code Editor:

Previous: savez_compressed() function
Next: savetxt() function



Share this Tutorial / Exercise on : Facebook and Twitter