bundles / numpy latest / numpy / loadtxt
_ArrayFunctionDispatcher
numpy:loadtxt
source: /dev/numpy/build-install/usr/lib/python3.14/site-packages/numpy/lib/_npyio_impl.py :1118
Signature
def loadtxt ( fname , dtype = <class 'float'> , comments = # , delimiter = None , converters = None , skiprows = 0 , usecols = None , unpack = False , ndmin = 0 , encoding = None , max_rows = None , * , quotechar = None , like = None ) Summary
Load data from a text file.
Parameters
fname: file, str, pathlib.Path, list of str, generatorFile, filename, list, or generator to read. If the filename extension is
.gzor.bz2, the file is first decompressed. Note that generators must return bytes or strings. The strings in a list or produced by a generator are treated as lines.dtype: data-type, optionalData-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.
comments: str or sequence of str or None, optionalThe characters or list of characters used to indicate the start of a comment. None implies no comments. For backwards compatibility, byte strings will be decoded as 'latin1'. The default is '#'.
delimiter: str, optionalThe character used to separate the values. For backwards compatibility, byte strings will be decoded as 'latin1'. The default is whitespace.
converters: dict or callable, optionalConverter functions to customize value parsing. If
convertersis callable, the function is applied to all columns, else it must be a dict that maps column number to a parser function. See examples for further details. Default: None.skiprows: int, optionalSkip the first
skiprowslines, including comments; default: 0.usecols: int or sequence, optionalWhich 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.unpack: bool, optionalIf 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.ndmin: int, optionalThe returned array will have at least
ndmindimensions. Otherwise mono-dimensional axes will be squeezed. Legal values: 0 (default), 1 or 2.encoding: str, optionalEncoding 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 None.
max_rows: int, optionalRead
max_rowsrows of content afterskiprowslines. The default is to read all the rows. Note that empty rows containing no data such as empty lines and comment lines are not counted towardsmax_rows, while such lines are counted inskiprows.quotechar: unicode character or None, optionalThe character used to denote the start and end of a quoted item. Occurrences of the delimiter or comment characters are ignored within a quoted item. The default value is
quotechar=None, which means quoting support is disabled.If two consecutive instances of
quotecharare found within a quoted field, the first is treated as an escape character. See examples.like: array_like, optionalReference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as
likesupports the__array_function__protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.
Returns
out: ndarrayData 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.
Each row in the input text file must have the same number of values to be able to read all values. If all rows do not have same number of values, a subset of up to n columns (where n is the least number of values present in all rows) can be read by specifying the columns via usecols.
The strings produced by the Python float.hex method can be used as input for floats.
Examples
import numpy as np from io import StringIO # StringIO behaves like a file object c = StringIO("0 1\n2 3") np.loadtxt(c)✓
d = StringIO("M 21 72\nF 35 58") np.loadtxt(d, dtype={'names': ('gender', 'age', 'weight'), 'formats': ('S1', 'i4', 'f4')})✓
c = StringIO("1,0,2\n3,0,4") x, y = np.loadtxt(c, delimiter=',', usecols=(0, 2), unpack=True) x y✓
s = StringIO("1.618, 2.296\n3.141, 4.669\n") conv = { 0: lambda x: np.floor(float(x)), # conversion fn for column 0 1: lambda x: np.ceil(float(x)), # conversion fn for column 1 } np.loadtxt(s, delimiter=",", converters=conv)✓
s = StringIO("0xDE 0xAD\n0xC0 0xDE") import functools conv = functools.partial(int, base=16) np.loadtxt(s, converters=conv)✓
s = StringIO("10.01 31.25-\n19.22 64.31\n17.57- 63.94") def conv(fld): return -float(fld[:-1]) if fld.endswith("-") else float(fld) np.loadtxt(s, converters=conv)✓
s = StringIO("1 2.7 100_000")
✓np.loadtxt(s, converters=float)
✗def conv(val): try: return float(val) except ValueError: return float.fromhex(val) s = StringIO("1, 2.5, 3_000, 0b4, 0x1.4000000000000p+2") np.loadtxt(s, delimiter=",", converters=conv)✓
s = StringIO("10.01 31.25-\n19.22 64.31\n17.57- 63.94") conv = lambda x: -float(x[:-1]) if x.endswith("-") else float(x) np.loadtxt(s, converters=conv)✓
s = StringIO('"alpha, #42", 10.0\n"beta, #64", 2.0\n') dtype = np.dtype([("label", "U12"), ("value", float)])✓
np.loadtxt(s, dtype=dtype, delimiter=",", quotechar='"')
✗s = StringIO('"alpha, #42" 10.0\n"beta, #64" 2.0\n') dtype = np.dtype([("label", "U12"), ("value", float)])✓
np.loadtxt(s, dtype=dtype, delimiter=None, quotechar='"')
✗s = StringIO('"Hello, my name is ""Monty""!"') np.loadtxt(s, dtype="U", delimiter=",", quotechar='"')✓
d = StringIO("1 2\n2 4\n3 9 12\n4 16 20") np.loadtxt(d, usecols=(0, 1))✓
See also
- fromregex
- fromstring
- genfromtxt
Load data with missing values handled as specified.
- load
- scipy.io.loadmat
reads MATLAB data files
Aliases
-
numpy.loadtxt -
numpy.lib._npyio_impl._loadtxt_with_like