K i̓.dZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl m Z ddlm Z ddl ZddlmZddlmZddlmZmZddlmZmZdd lmZmZd d lmZd d lmZd d l m!Z!d dl"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-gdZ.ej^ej`dZ0GddZ1dZ2edGdde Z3ed dd#Zfd&Z?d'Z@d?d(ZAd)ZBd'Z@d*d+d,d-ddddddejdd. d/ZDeedeEd+ddddddddf ddd0d1ZFe0eFZG d@d2ZHe0eH dAd4ZIeddBd5ZJeedeEd+dddddddddd3jeLe'jd6ddd7ddddddfddd8d9ZNe0eNZOd:ZPd;ZQy)Cz IO related functions. N)Mapping) itemgetter) overrides)_load_from_filelike)packbits unpackbits)finalize_array_function_like set_module)asbytes asunicode)format) DataSource)_MAX_HEADER_SIZE) ConversionWarningConverterErrorConverterLockError LineSplitter NameValidatorStringConverter _decode_line_is_string_like easy_dtype flatten_dtypehas_nested_fields) savetxtloadtxt genfromtxtloadsavesavezsavez_compressedrr fromregexnumpy)modulec"eZdZdZdZdZdZy)BagObja BagObj(obj) Convert attribute look-ups to getitems on the object passed in. Parameters ---------- obj : class instance Object on which attribute look-up is performed. Examples -------- >>> import numpy as np >>> from numpy.lib._npyio_impl import BagObj as BO >>> class BagDemo: ... def __getitem__(self, key): # An instance of BagObj(BagDemo) ... # will call this method when any ... # attribute look-up is required ... result = "Doesn't matter what you want, " ... return result + "you're gonna get this" ... >>> demo_obj = BagDemo() >>> bagobj = BO(demo_obj) >>> bagobj.hello_there "Doesn't matter what you want, you're gonna get this" >>> bagobj.I_can_be_anything "Doesn't matter what you want, you're gonna get this" c8tj||_yN)weakrefproxy_obj)selfobjs [/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/numpy/lib/_npyio_impl.py__init__zBagObj.__init__QsMM#& ch tj|d|S#t$r t|dwxYw)Nr,)object__getattribute__KeyErrorAttributeErrorr-keys r/r4zBagObj.__getattribute__Us; 0**48= = 0 %4 / 0s1c\ttj|djS)z Enables dir(bagobj) to list the files in an NpzFile. This also enables tab-completion in an interpreter or IPython. r,)listr3r4keysr-s r/__dir__zBagObj.__dir__[s% F++D&9>>@AAr1N)__name__ __module__ __qualname____doc__r0r4r=r1r/r'r'2s<'0 Br1r'ct|dstj|}ddl}d|d<|j|g|i|S)z Create a ZipFile. Allows for Zip64, and the `file` argument can accept file, str, or pathlib.Path objects. `args` and `kwargs` are passed to the zipfile.ZipFile constructor. readrNT allowZip64)hasattrosfspathzipfileZipFile)fileargskwargsrIs r/zipfile_factoryrNdsC 4 yyF< 7??4 1$ 1& 11r1znumpy.lib.npyioc~eZdZdZdZdZdZ deddZdZ dZ dZ d Z d Z d Zd Zd ZdZddZdZdZdZy)NpzFilea NpzFile(fid) A dictionary-like object with lazy-loading of files in the zipped archive provided on construction. `NpzFile` is used to load files in the NumPy ``.npz`` data archive format. It assumes that files in the archive have a ``.npy`` extension, other files are ignored. The arrays and file strings are lazily loaded on either getitem access using ``obj['key']`` or attribute lookup using ``obj.f.key``. A list of all files (without ``.npy`` extensions) can be obtained with ``obj.files`` and the ZipFile object itself using ``obj.zip``. Attributes ---------- files : list of str List of all files in the archive with a ``.npy`` extension. zip : ZipFile instance The ZipFile object initialized with the zipped archive. f : BagObj instance An object on which attribute can be performed as an alternative to getitem access on the `NpzFile` instance itself. allow_pickle : bool, optional Allow loading pickled data. Default: False pickle_kwargs : dict, optional Additional keyword arguments to pass on to pickle.load. These are only useful when loading object arrays saved on Python 2. max_header_size : int, optional Maximum allowed size of the header. Large headers may not be safe to load securely and thus require explicitly passing a larger value. See :py:func:`ast.literal_eval()` for details. This option is ignored when `allow_pickle` is passed. In that case the file is by definition trusted and the limit is unnecessary. Parameters ---------- fid : file, str, or pathlib.Path The zipped archive to open. This is either a file-like object or a string containing the path to the archive. own_fid : bool, optional Whether NpzFile should close the file handle. Requires that `fid` is a file-like object. Examples -------- >>> import numpy as np >>> from tempfile import TemporaryFile >>> outfile = TemporaryFile() >>> x = np.arange(10) >>> y = np.sin(x) >>> np.savez(outfile, x=x, y=y) >>> _ = outfile.seek(0) >>> npz = np.load(outfile) >>> isinstance(npz, np.lib.npyio.NpzFile) True >>> npz NpzFile 'object' with keys: x, y >>> sorted(npz.files) ['x', 'y'] >>> npz['x'] # getitem access array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> npz.f.x # attribute lookup array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) Nmax_header_sizect|}|j}|Dcgc]}|jdc}|_t t |j||_|j jt ||||_||_ ||_ ||_t||_ |r||_ yycc}w)N.npy)rNnamelist removesuffixfilesdictzip_filesupdate allow_picklerS pickle_kwargsr'ffid) r-r`own_fidr]r^rS_zipr[names r/r0zNpzFile.__init__s s#r?r@rArZr`rrr0rerlrhrprsrvrrrrrr;rrBr1r/rPrPsspEN C C8=#!1$  (6$ @"/ # " $r1rPFTrRc |dvr td||d}tj5}t|dr|}d} n0|j t t j|d}d} d} d } ttj} |j| } | s td |jt| t|  d | j| | fr+|j!t#|| ||| }|cd d d S| tjk(rI|r%|rd}tj$|||cd d d Stj&||||cd d d S|s td t)j*|fi|cd d d S#t,$r}t)j.d|d|d }~wwxYw#1swYy xYw)a Load arrays or pickled objects from ``.npy``, ``.npz`` or pickled files. .. warning:: Loading files that contain object arrays uses the ``pickle`` module, which is not secure against erroneous or maliciously constructed data. Consider passing ``allow_pickle=False`` to load data that is known not to contain object arrays for the safer handling of untrusted sources. Parameters ---------- file : file-like object, string, or pathlib.Path The file to read. File-like objects must support the ``seek()`` and ``read()`` methods and must always be opened in binary mode. Pickled files require that the file-like object support the ``readline()`` method as well. mmap_mode : {None, 'r+', 'r', 'w+', 'c'}, optional If not None, then memory-map the file, using the given mode (see `numpy.memmap` for a detailed description of the modes). A memory-mapped array is kept on disk. However, it can be accessed and sliced like any ndarray. Memory mapping is especially useful for accessing small fragments of large files without reading the entire file into memory. allow_pickle : bool, optional Allow loading pickled object arrays stored in npy files. Reasons for disallowing pickles include security, as loading pickled data can execute arbitrary code. If pickles are disallowed, loading object arrays will fail. Default: False fix_imports : bool, optional Only useful when loading Python 2 generated pickled files, which includes npy/npz files containing object arrays. If `fix_imports` is True, pickle will try to map the old Python 2 names to the new names used in Python 3. encoding : str, optional What encoding to use when reading Python 2 strings. Only useful when loading Python 2 generated pickled files, which includes npy/npz files containing object arrays. Values other than 'latin1', 'ASCII', and 'bytes' are not allowed, as they can corrupt numerical data. Default: 'ASCII' max_header_size : int, optional Maximum allowed size of the header. Large headers may not be safe to load securely and thus require explicitly passing a larger value. See :py:func:`ast.literal_eval()` for details. This option is ignored when `allow_pickle` is passed. In that case the file is by definition trusted and the limit is unnecessary. Returns ------- result : array, tuple, dict, etc. Data stored in the file. For ``.npz`` files, the returned instance of NpzFile class must be closed to avoid leaking file descriptors. Raises ------ OSError If the input file does not exist or cannot be read. UnpicklingError If ``allow_pickle=True``, but the file cannot be loaded as a pickle. ValueError The file contains an object array, but ``allow_pickle=False`` given. EOFError When calling ``np.load`` multiple times on the same file handle, if all data has already been read See Also -------- save, savez, savez_compressed, loadtxt memmap : Create a memory-map to an array stored in a file on disk. lib.format.open_memmap : Create or load a memory-mapped ``.npy`` file. Notes ----- - If the file contains pickle data, then whatever object is stored in the pickle is returned. - If the file is a ``.npy`` file, then a single array is returned. - If the file is a ``.npz`` file, then a dictionary-like object is returned, containing ``{filename: array}`` key-value pairs, one for each file in the archive. - If the file is a ``.npz`` file, the returned value supports the context manager protocol in a similar fashion to the open function:: with load('foo.npz') as data: a = data['a'] The underlying file descriptor is closed when exiting the 'with' block. Examples -------- >>> import numpy as np Store data to disk, and load it again: >>> np.save('/tmp/123', np.array([[1, 2, 3], [4, 5, 6]])) >>> np.load('/tmp/123.npy') array([[1, 2, 3], [4, 5, 6]]) Store compressed data to disk, and load it again: >>> a=np.array([[1, 2, 3], [4, 5, 6]]) >>> b=np.array([1, 2]) >>> np.savez('/tmp/123.npz', a=a, b=b) >>> data = np.load('/tmp/123.npz') >>> data['a'] array([[1, 2, 3], [4, 5, 6]]) >>> data['b'] array([1, 2]) >>> data.close() Mem-map the stored array, and then access the second row directly from disk: >>> X = np.load('/tmp/123.npy', mmap_mode='r') >>> X[1, :] memmap([4, 5, 6]) )ASCIIlatin1r}z.encoding must be 'ASCII', 'latin1', or 'bytes')encoding fix_importsrDFrbTsPKsPKzNo data left in filer )rar]r^rSNl)moderSrxzThis file contains pickled (object) data. If you trust the file you can load it unsafely using the `allow_pickle=` keyword argument or `pickle.load()`.zFailed to interpret file z as a pickle) ValueError contextlib ExitStackrF enter_contextryrGrHrurrzrDEOFErrorr{min startswithpop_allrP open_memmapr|pickler ExceptionUnpicklingError)rK mmap_moder]rrrSr^stackr`ra _ZIP_PREFIX _ZIP_SUFFIXNr~retes r/rr7st33IJJ!)+FM    0M5 4 CG%%d299T?D&ABCG$ # ## $ 12 2 #aU$$a(   [+6 7 MMO#w\(5*9;C30M0M4f)) )&+O))$Y:IK?0M0MD((<7D9HJE0M0MN  KLL M{{38-8[0M0M\ M,,/x|DFKLM M]0M0Ms<CF> 0F>F>& F>4F F;F66F;;F>>Gc|fSr)rB)rKarrr]rs r/_save_dispatcherrs 6Mr1c|tjurtjdtdt |drt j|}n7tj|}|jds|dz}t|d}|5}tj|}tj|||d|id d d y #1swYy xYw) a Save an array to a binary file in NumPy ``.npy`` format. Parameters ---------- file : file, str, or pathlib.Path File or filename to which the data is saved. If file is a file-object, then the filename is unchanged. If file is a string or Path, a ``.npy`` extension will be appended to the filename if it does not already have one. arr : array_like Array data to be saved. allow_pickle : bool, optional Allow saving object arrays using Python pickles. Reasons for disallowing pickles include security (loading pickled data can execute arbitrary code) and portability (pickled objects may not be loadable on different Python installations, for example if the stored objects require libraries that are not available, and not all pickled data is compatible between different versions of Python). Default: True fix_imports : bool, optional The `fix_imports` flag is deprecated and has no effect. .. deprecated:: 2.1 This flag is ignored since NumPy 1.17 and was only needed to support loading in Python 2 some files written in Python 3. See Also -------- savez : Save several arrays into a ``.npz`` archive savetxt, load Notes ----- For a description of the ``.npy`` format, see :py:mod:`numpy.lib.format`. Any data saved to the file is appended to the end of the file. Examples -------- >>> import numpy as np >>> from tempfile import TemporaryFile >>> outfile = TemporaryFile() >>> x = np.arange(10) >>> np.save(outfile, x) >>> _ = outfile.seek(0) # Only needed to simulate closing & reopening file >>> np.load(outfile) array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> with open('test.npy', 'wb') as f: ... np.save(f, np.array([1, 2])) ... np.save(f, np.array([1, 3])) >>> with open('test.npy', 'rb') as f: ... a = np.load(f) ... b = np.load(f) >>> print(a, b) # [1 2] [1 3] zQThe 'fix_imports' flag is deprecated and has no effect. (Deprecated in NumPy 2.1) stacklevelwriterUwbrr]r^N)np_NoValuewarningswarnDeprecationWarningrFr nullcontextrGrHendswithry asanyarrayr write_array)rKrr]rfile_ctxr`s r/r r s@"++%  ( 1 .tW))$/yy}}V$&=Dd# GSmmC 3,*7)E GGGGs 1CC r]c/XK|Ed{|jEd{y77wr)rrKr]rLkwdss r/_savez_dispatcherrL%OO{{}*&*(**c$t|||d|y)a Save several arrays into a single file in uncompressed ``.npz`` format. Provide arrays as keyword arguments to store them under the corresponding name in the output file: ``savez(fn, x=x, y=y)``. If arrays are specified as positional arguments, i.e., ``savez(fn, x, y)``, their names will be `arr_0`, `arr_1`, etc. Parameters ---------- file : file, str, or pathlib.Path Either the filename (string) or an open file (file-like object) where the data will be saved. If file is a string or a Path, the ``.npz`` extension will be appended to the filename if it is not already there. args : Arguments, optional Arrays to save to the file. Please use keyword arguments (see `kwds` below) to assign names to arrays. Arrays specified as args will be named "arr_0", "arr_1", and so on. allow_pickle : bool, optional Allow saving object arrays using Python pickles. Reasons for disallowing pickles include security (loading pickled data can execute arbitrary code) and portability (pickled objects may not be loadable on different Python installations, for example if the stored objects require libraries that are not available, and not all pickled data is compatible between different versions of Python). Default: True kwds : Keyword arguments, optional Arrays to save to the file. Each array will be saved to the output file with its corresponding keyword name. Returns ------- None See Also -------- save : Save a single array to a binary file in NumPy format. savetxt : Save an array to a file as plain text. savez_compressed : Save several arrays into a compressed ``.npz`` archive Notes ----- The ``.npz`` file format is a zipped archive of files named after the variables they contain. The archive is not compressed and each file in the archive contains one variable in ``.npy`` format. For a description of the ``.npy`` format, see :py:mod:`numpy.lib.format`. When opening the saved ``.npz`` file with `load` a `~lib.npyio.NpzFile` object is returned. This is a dictionary-like object which can be queried for its list of arrays (with the ``.files`` attribute), and for the arrays themselves. Keys passed in `kwds` are used as filenames inside the ZIP archive. Therefore, keys should be valid filenames; e.g., avoid keys that begin with ``/`` or contain ``.``. When naming variables with keyword arguments, it is not possible to name a variable ``file``, as this would cause the ``file`` argument to be defined twice in the call to ``savez``. Examples -------- >>> import numpy as np >>> from tempfile import TemporaryFile >>> outfile = TemporaryFile() >>> x = np.arange(10) >>> y = np.sin(x) Using `savez` with \*args, the arrays are saved with default names. >>> np.savez(outfile, x, y) >>> _ = outfile.seek(0) # Only needed to simulate closing & reopening file >>> npzfile = np.load(outfile) >>> npzfile.files ['arr_0', 'arr_1'] >>> npzfile['arr_0'] array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) Using `savez` with \**kwds, the arrays are saved with the keyword names. >>> outfile = TemporaryFile() >>> np.savez(outfile, x=x, y=y) >>> _ = outfile.seek(0) >>> npzfile = np.load(outfile) >>> sorted(npzfile.files) ['x', 'y'] >>> npzfile['x'] array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) FrN_savezrs r/r!r!Qsz 4tU>r1c/XK|Ed{|jEd{y77wr)rrs r/_savez_compressed_dispatcherrrrc$t|||d|y)a% Save several arrays into a single file in compressed ``.npz`` format. Provide arrays as keyword arguments to store them under the corresponding name in the output file: ``savez_compressed(fn, x=x, y=y)``. If arrays are specified as positional arguments, i.e., ``savez_compressed(fn, x, y)``, their names will be `arr_0`, `arr_1`, etc. Parameters ---------- file : file, str, or pathlib.Path Either the filename (string) or an open file (file-like object) where the data will be saved. If file is a string or a Path, the ``.npz`` extension will be appended to the filename if it is not already there. args : Arguments, optional Arrays to save to the file. Please use keyword arguments (see `kwds` below) to assign names to arrays. Arrays specified as args will be named "arr_0", "arr_1", and so on. allow_pickle : bool, optional Allow saving object arrays using Python pickles. Reasons for disallowing pickles include security (loading pickled data can execute arbitrary code) and portability (pickled objects may not be loadable on different Python installations, for example if the stored objects require libraries that are not available, and not all pickled data is compatible between different versions of Python). Default: True kwds : Keyword arguments, optional Arrays to save to the file. Each array will be saved to the output file with its corresponding keyword name. Returns ------- None See Also -------- numpy.save : Save a single array to a binary file in NumPy format. numpy.savetxt : Save an array to a file as plain text. numpy.savez : Save several arrays into an uncompressed ``.npz`` file format numpy.load : Load the files created by savez_compressed. Notes ----- The ``.npz`` file format is a zipped archive of files named after the variables they contain. The archive is compressed with ``zipfile.ZIP_DEFLATED`` and each file in the archive contains one variable in ``.npy`` format. For a description of the ``.npy`` format, see :py:mod:`numpy.lib.format`. When opening the saved ``.npz`` file with `load` a `~lib.npyio.NpzFile` object is returned. This is a dictionary-like object which can be queried for its list of arrays (with the ``.files`` attribute), and for the arrays themselves. Examples -------- >>> import numpy as np >>> test_array = np.random.rand(3, 2) >>> test_vector = np.random.rand(4) >>> np.savez_compressed('/tmp/123', a=test_array, b=test_vector) >>> loaded = np.load('/tmp/123.npz') >>> print(np.array_equal(test_array, loaded['a'])) True >>> print(np.array_equal(test_vector, loaded['b'])) True TrNrrs r/r"r"sP 4tT =r1cddl}t|ds+tj|}|j ds|dz}|}t |D]/\}} d|z} | |j vrtd| | || <1|r |j} n |j} t|d| } |jD]U\} } | dz} tj| } | j| dd 5}tj || || dddW | j#y#1swYsxYw#| j#wxYw) Nrrz.npzzarr_%dz*Cannot use un-named variables and keyword w)r compressionrUT) force_zip64r)rIrFrGrHr enumerater;r ZIP_DEFLATED ZIP_STOREDrNrrrryrrrh)rKrLrcompressr]r^rInamedictivalr8rzipffnamer`s r/rrsL 4 !yy}}V$&=DHD/3l (--/ !@ @ @  @  @ @ s%%AD+)D D+D( $D++D=c(|dvrtd|y)zJust checks if the param ndmin is supported on _ensure_ndmin_ndarray. It is intended to be used as verification before running anything expensive. e.g. loadtxt, genfromtxt )rr rz Illegal value of ndmin keyword: N)rndmins r/!_ensure_ndmin_ndarray_check_paramr&s$ I;E7CDDr1rc|j|kDrtj|}|j|kr@|dk(rtj|}|S|dk(rtj|j }|S)aThis is a helper function of loadtxt and genfromtxt to ensure proper minimum dimension as requested ndim : int. Supported values 1, 2, 3 ^^ whenever this changes, keep in sync with _ensure_ndmin_ndarray_check_param r r)ndimrsqueeze atleast_1d atleast_2dT)ars r/_ensure_ndmin_ndarrayr0sg vv~ JJqM vv~ A: a A HaZ a ""A Hr1iPc tj||dkrt|dy#t$rt|ddwxYw)Nz must be an integerrz must be nonnegative)operatorindex TypeErrorr)valuercs r/_check_nonneg_intrKs]@u qyD6!5677 @4& 3454?@s +Ac#K|D]C}t|tr|j|}|D]}|j|dd}|Eyw)a Generator that consumes a line iterated iterable and strips out the multiple (or multi-character) comments from lines. This is a pre-processing step to achieve feature parity with loadtxt (we assume that this feature is a nieche feature). r rN)rr}decodesplit)iterablecommentsrlinecs r/_preprocess_commentsrTsZ dE ";;x(D 'A::a#A&D ' sA A ,#"j) delimitercommentquoteimaginary_unitusecols skiplinesmax_rows convertersrunpackdtyperc d} | dk(rd} d} | tdtj| } d}| jdvro| tjdtjdtjd tjd hvr| }tjt} | t |}t | |d}n}d |vr td t|}d}t|d k(rd}nPt|dk(r,t|d tr/t|d dk(r|d }d}n||vrtd|d|d| | tdt|dk7r tdt|| t|nd}tj}d} t|tj rtj"|}t|trUtj$j&j)|d| }| t+|dd} tj,|}|}d}n| t+|dd} t/|}|5||r t/|}d}t3||| }|t5|||||||||| | ||  }n|r t/|}d}d}|dk(rd}g}|d k7rv|d krt6}nt9t6|}t5|||||||||| | || |}|j;|j=|d }|d k\r||z}t||krn|d k7rvt|dkDrt|dd k(r|d=t|dk(r|d }ntj>|d }dddtA| }|jBr2|jBd d k(r tEjFd |d!tHd"#| rA|j}|jJ|jJDcgc]}|| c}S|jLS|S#t$r|g}YZwxYw#t$r}tdt1|d|d}~wwxYw#1swYxYwcc}w)$a Read a NumPy array from a text file. This is a helper function for loadtxt. Parameters ---------- fname : file, str, or pathlib.Path The filename or the file to be read. delimiter : str, optional Field delimiter of the fields in line of the file. Default is a comma, ','. If None any sequence of whitespace is considered a delimiter. comment : str or sequence of str or None, optional Character that begins a comment. All text from the comment character to the end of the line is ignored. Multiple comments or multiple-character comment strings are supported, but may be slower and `quote` must be empty if used. Use None to disable all use of comments. quote : str or None, optional Character that is used to quote string fields. Default is '"' (a double quote). Use None to disable quote support. imaginary_unit : str, optional Character that represent the imaginary unit `sqrt(-1)`. Default is 'j'. usecols : array_like, optional A one-dimensional array of integer column numbers. These are the columns from the file to be included in the array. If this value is not given, all the columns are used. skiplines : int, optional Number of lines to skip before interpreting the data in the file. max_rows : int, optional Maximum number of rows of data to read. Default is to read the entire file. converters : dict or callable, optional A function to parse all columns strings into the desired value, or a dictionary mapping column number to a parser function. 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, e.g. ``converters = lambda s: float(s.strip() or 0)`` will convert empty fields to 0. Default: None ndmin : int, optional Minimum dimension of the array returned. Allowed values are 0, 1 or 2. Default is 0. unpack : bool, optional If True, the returned array is transposed, so that arguments may be unpacked using ``x, y, z = read(...)``. When used with a structured data-type, arrays are returned for each field. Default is False. dtype : numpy data type A NumPy dtype instance, can be a structured dtype to map to the columns of the file. encoding : str, optional Encoding used to decode the inputfile. The special value 'bytes' (the default) enables backwards-compatible behavior for `converters`, ensuring that inputs to the converter functions are encoded bytes objects. The special value 'bytes' has no additional effect if ``converters=None``. If encoding is ``'bytes'`` or ``None``, the default system encoding is used. Returns ------- ndarray NumPy array. Fr}NTza dtype must be provided.SUMS0U0M8m8zJcomments cannot be an empty string. Use comments=None to disable comments.rr zComment characters 'z ' cannot include the delimiter ''zwhen multiple comments or a multi-character comment is given, quotes are not supported. In this case quotechar must be set to None.zlen(imaginary_unit) must be 1.rtrrrzGfname must be a string, filehandle, list of strings, or generator. Got instead.) rrrrrrrrrrfilelikebyte_convertersS) rrrrrrrrrrrrc_byte_converters)axisrz#loadtxt: input contained no data: "r)categoryr)'rrrkindr3r:rrtuplerurrrrrrGPathLikerHlib _datasourceryrclosingrrtyperr_loadtxt_chunksizerappendastype concatenatershaperr UserWarningnamesr)rrrrrrrrrrrrrrread_dtype_via_object_chunksrfh_closing_ctxrfhdatarrrchunks chunk_sizenext_arrdtfields r/_readr.jsJO7 }344 HHUOE#'  zzUu HHTNBHHTNBHHTNBHHTN)L L (-$  7mG&e, =$ > x=A H ]a (1+s+HQK0@A0E"1+ ( "&xj1'[+    '( (  >a9::i (#++-NH@ eR[[ )IIe$E eS !##((x(HB"2z8<'//3NDH"5*h?;D ?5  Dz 'hAD ' /% 7%-9x%U!H / 1CDz  % +s2$(!Fa-a$   YY 88 ,.HH55CJ5 555L E iG J @!!%e Y 89>? @@ ?5?5h6sE0 P"B.PCQ!A Q) Q PP Q"P;;QQ ) quotecharlikec | t| |||||||||| |  St|tr|jd|tj }|} | It| t tfr| g} | Dcgc]%}t|tr|jdn|'} }t|tr|jd}t||| ||||||| | |  }|Scc}w)a% Load data from a text file. Parameters ---------- fname : file, str, pathlib.Path, list of str, generator File, filename, list, or generator to read. If the filename extension is ``.gz`` or ``.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, optional 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. comments : str or sequence of str or None, optional The 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, optional The character used to separate the values. For backwards compatibility, byte strings will be decoded as 'latin1'. The default is whitespace. .. versionchanged:: 1.23.0 Only single character delimiters are supported. Newline characters cannot be used as the delimiter. converters : dict or callable, optional Converter functions to customize value parsing. If `converters` is 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. .. versionchanged:: 1.23.0 The ability to pass a single callable to be applied to all columns was added. skiprows : int, optional Skip the first `skiprows` lines, including comments; default: 0. usecols : int or sequence, optional 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. unpack : bool, optional 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. ndmin : int, optional The returned array will have at least `ndmin` dimensions. Otherwise mono-dimensional axes will be squeezed. Legal values: 0 (default), 1 or 2. encoding : str, optional 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 None. .. versionchanged:: 2.0 Before NumPy 2, the default was ``'bytes'`` for Python 2 compatibility. The default is now ``None``. max_rows : int, optional Read `max_rows` rows of content after `skiprows` lines. 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 towards `max_rows`, while such lines are counted in `skiprows`. .. versionchanged:: 1.23.0 Lines containing no data, including comment lines (e.g., lines starting with '#' or as specified via `comments`) are not counted towards `max_rows`. quotechar : unicode character or None, optional The 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 `quotechar` are found within a quoted field, the first is treated as an escape character. See examples. .. versionadded:: 1.23.0 ${ARRAY_FUNCTION_LIKE} .. versionadded:: 1.20.0 Returns ------- out : ndarray Data read from the text file. See Also -------- load, fromstring, fromregex genfromtxt : Load data with missing values handled as specified. scipy.io.loadmat : reads MATLAB data files 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) array([[0., 1.], [2., 3.]]) >>> d = StringIO("M 21 72\nF 35 58") >>> np.loadtxt(d, dtype={'names': ('gender', 'age', 'weight'), ... 'formats': ('S1', 'i4', 'f4')}) array([(b'M', 21, 72.), (b'F', 35, 58.)], dtype=[('gender', 'S1'), ('age', '>> c = StringIO("1,0,2\n3,0,4") >>> x, y = np.loadtxt(c, delimiter=',', usecols=(0, 2), unpack=True) >>> x array([1., 3.]) >>> y array([2., 4.]) The `converters` argument is used to specify functions to preprocess the text prior to parsing. `converters` can be a dictionary that maps preprocessing functions to each column: >>> 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) array([[1., 3.], [3., 5.]]) `converters` can be a callable instead of a dictionary, in which case it is applied to all columns: >>> s = StringIO("0xDE 0xAD\n0xC0 0xDE") >>> import functools >>> conv = functools.partial(int, base=16) >>> np.loadtxt(s, converters=conv) array([[222., 173.], [192., 222.]]) This example shows how `converters` can be used to convert a field with a trailing minus sign into a negative number. >>> 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) array([[ 10.01, -31.25], [ 19.22, 64.31], [-17.57, 63.94]]) Using a callable as the converter can be particularly useful for handling values with different formatting, e.g. floats with underscores: >>> s = StringIO("1 2.7 100_000") >>> np.loadtxt(s, converters=float) array([1.e+00, 2.7e+00, 1.e+05]) This idea can be extended to automatically handle values specified in many different formats, such as hex values: >>> 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) array([1.0e+00, 2.5e+00, 3.0e+03, 1.8e+02, 5.0e+00]) Or a format where the ``-`` sign comes after the number: >>> 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) array([[ 10.01, -31.25], [ 19.22, 64.31], [-17.57, 63.94]]) Support for quoted fields is enabled with the `quotechar` parameter. Comment and delimiter characters are ignored when they appear within a quoted item delineated by `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=",", quotechar='"') array([('alpha, #42', 10.), ('beta, #64', 2.)], dtype=[('label', '>> 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='"') array([('alpha, #42', 10.), ('beta, #64', 2.)], dtype=[('label', '>> s = StringIO('"Hello, my name is ""Monty""!"') >>> np.loadtxt(s, dtype="U", delimiter=",", quotechar='"') array('Hello, my name is "Monty"!', dtype='>> d = StringIO("1 2\n2 4\n3 9 12\n4 16 20") >>> np.loadtxt(d, usecols=(0, 1)) array([[ 1., 2.], [ 2., 4.], [ 3., 9.], [ 4., 16.]]) ) rrrrskiprowsrrrrrr) rrrrrrrrrrr)_loadtxt_with_likerr}rrfloat64rr.)rrrrrr2rrrrrr/r0rxrs r/rrksd ! %ux9!Hg   )U#" } G gU| ,iGGNPBC*Q"6AHHX A =PP)U#$$X. UGy%7UX! 4C JPs.*Cc |fSr)rB) rXfmtrnewlineheaderfooterrrs r/_savetxt_dispatcherr<s  4Kr1r c Gdd} d} t|tjrtj|}t |rIt |dj tjjj |d|} d} n%t|dr| ||xsd} n td  tj|}|jd k(s|jd kDrtd |jz|jd k(rX|jj"tj |j"}d } n/t%|jj} n|j&d } tj(|} t+|t,t.fvr7t%|| k7rt1dt3||j5|}nt|t2rd|j7d}td|}|d k(r(| rd|d|dg| z}n|g| z}|j5|}n&| r |d | zk7r|| s|| k7r||}ntd|t%|d kDr,|j9dd|z}| j;||z|z| rj|D]d}g}|D])}|j=|j>|j@f+|t/|z|z}| j;|j9ddfn*|D]%} |t/|z|z}| j;|'t%|d kDr,|j9dd|z}| j;||z|z| r| j yy#tB$r+}tCdt3|jd|d|d}~wwxYw#| r| j wwxYw)ae Save an array to a text file. Parameters ---------- fname : filename, file handle or pathlib.Path If the filename ends in ``.gz``, the file is automatically saved in compressed gzip format. `loadtxt` understands gzipped files transparently. X : 1D or 2D array_like Data to be saved to a text file. fmt : str or sequence of strs, optional A single format (%10.5f), a sequence of formats, or a multi-format string, e.g. 'Iteration %d -- %10.5f', in which case `delimiter` is ignored. For complex `X`, the legal options for `fmt` are: * a single specifier, ``fmt='%.4e'``, resulting in numbers formatted like ``' (%s+%sj)' % (fmt, fmt)`` * a full string specifying every real and imaginary part, e.g. ``' %.4e %+.4ej %.4e %+.4ej %.4e %+.4ej'`` for 3 columns * a list of specifiers, one per column - in this case, the real and imaginary part must have separate specifiers, e.g. ``['%.3e + %.3ej', '(%.15e%+.15ej)']`` for 2 columns delimiter : str, optional String or character separating columns. newline : str, optional String or character separating lines. header : str, optional String that will be written at the beginning of the file. footer : str, optional String that will be written at the end of the file. comments : str, optional String that will be prepended to the ``header`` and ``footer`` strings, to mark them as comments. Default: '# ', as expected by e.g. ``numpy.loadtxt``. encoding : {None, str}, optional Encoding used to encode the outputfile. Does not apply to output streams. If the encoding is something other than 'bytes' or 'latin1' you will not be able to load the file in NumPy versions < 1.14. Default is 'latin1'. See Also -------- save : Save an array to a binary file in NumPy ``.npy`` format savez : Save several arrays into an uncompressed ``.npz`` archive savez_compressed : Save several arrays into a compressed ``.npz`` archive Notes ----- Further explanation of the `fmt` parameter (``%[flag]width[.precision]specifier``): flags: ``-`` : left justify ``+`` : Forces to precede result with + or -. ``0`` : Left pad the number with zeros instead of space (see width). width: Minimum number of characters to be printed. The value is not truncated if it has more characters. precision: - For integer specifiers (eg. ``d,i,o,x``), the minimum number of digits. - For ``e, E`` and ``f`` specifiers, the number of digits to print after the decimal point. - For ``g`` and ``G``, the maximum number of significant digits. - For ``s``, the maximum number of characters. specifiers: ``c`` : character ``d`` or ``i`` : signed decimal integer ``e`` or ``E`` : scientific notation with ``e`` or ``E``. ``f`` : decimal floating point ``g,G`` : use the shorter of ``e,E`` or ``f`` ``o`` : signed octal ``s`` : string of characters ``u`` : unsigned decimal integer ``x,X`` : unsigned hexadecimal integer This explanation of ``fmt`` is not complete, for an exhaustive specification see [1]_. References ---------- .. [1] `Format Specification Mini-Language `_, Python Documentation. Examples -------- >>> import numpy as np >>> x = y = z = np.arange(0.0,5.0,1.0) >>> np.savetxt('test.out', x, delimiter=',') # X is an array >>> np.savetxt('test.out', (x,y,z)) # x,y,z equal sized 1D arrays >>> np.savetxt('test.out', x, fmt='%1.4e') # use exponential notation c4eZdZdZdZdZdZdZdZdZ y) savetxt..WriteWrapz0Convert to bytes on bytestream inputs. cB||_||_|j|_yr))r'r first_writedo_write)r-r'rs r/r0z#savetxt..WriteWrap.__init__sDG$DM ,,DMr1c8|jjyr))r'rhr<s r/rhz savetxt..WriteWrap.closes GGMMOr1c&|j|yr))rBr-vs r/rz savetxt..WriteWrap.writes MM! r1ct|tr|jj|y|jj|j |j yr))rr}r'rencoderrEs r/ write_bytesz&savetxt..WriteWrap.write_bytess9!U# a  ahht}}56r1cL|jjt|yr))r'rr rEs r/ write_normalz'savetxt..WriteWrap.write_normal s GGMM)A, 'r1c |j||j|_y#t$r%|j||j|_YywxYwr))rKrrrIrEs r/rAz&savetxt..WriteWrap.first_writesL .!!!$!..  .  #!--  .s"%+AAN) r>r?r@rAr0rhrrIrKrArBr1r/ WriteWrapr?s%  -    7  ( .r1rMFwtrTrrz%fname must be a string or file handlerrz.Expected 1D or 2D array, got %dD array insteadr Nzfmt has wrong shape. %z$fmt has wrong number of % formats: z (+zj)z invalid fmt:  z+--zMismatch between array dtype ('z') and format specifier (''))"rrGrrHrryrhrrrrFrasarrayrrr$rrrur" iscomplexobjrr:rr6rrcountreplacerextendrealimagr)rr7r8rr9r:r;rrrMown_fhr'ncol iscomplex_Xr n_fmt_charserrorrowrow2numbersrFrs r/rrsb..BF%% % u UD! VV   $ $UD8 $ D  uh2( 3@AAE JJqM 66Q;!&&1*@166IK K VVq[ww}}$MM!$&&177==)771:Dooa(  9u %3x4$'=c#hZ%HII^^C(F S !))C.K!EcUKLEauAcU"-047C'D.C",T!: " t(; }SG45 5 v;?^^D$/:F HHX&0 1  /!CDEE  HHJ s26IN1M:A N1: N.&N))N..N11OcFd}t|dsCtj|}tjj j |d|}d} t|tjstj|}|j td|j}t|trt|tr t|}t|dstj |}|j#|}|rWt|dt$sDtj||jd}tj&|| }||_ntj&|| }||r|j)SS#|r|j)wwxYw) ay Construct an array from a text file, using regular expression parsing. The returned array is always a structured array, and is constructed from all matches of the regular expression in the file. Groups in the regular expression are converted to fields of the structured array. Parameters ---------- file : file, str, or pathlib.Path Filename or file object to read. .. versionchanged:: 1.22.0 Now accepts `os.PathLike` implementations. regexp : str or regexp Regular expression used to parse the file. Groups in the regular expression correspond to fields in the dtype. dtype : dtype or list of dtypes Dtype for the structured array; must be a structured datatype. encoding : str, optional Encoding used to decode the inputfile. Does not apply to input streams. Returns ------- output : ndarray The output array, containing the part of the content of `file` that was matched by `regexp`. `output` is always a structured array. Raises ------ TypeError When `dtype` is not a valid dtype for a structured array. See Also -------- fromstring, loadtxt Notes ----- Dtypes for structured arrays can be specified in several forms, but all forms specify at least the data type and field name. For details see `basics.rec`. Examples -------- >>> import numpy as np >>> from io import StringIO >>> text = StringIO("1312 foo\n1534 bar\n444 qux") >>> regexp = r"(\d+)\s+(...)" # match [digits, whitespace, anything] >>> output = np.fromregex(text, regexp, ... [('num', np.int64), ('key', 'S3')]) >>> output array([(1312, b'foo'), (1534, b'bar'), ( 444, b'qux')], dtype=[('num', '>> output['num'] array([1312, 1534, 444]) FrDr rTz$dtype must be a structured datatype.matchrr)rFrGrHrrrryrrr$rrDr}rr recompilefindallrarrayrh) rKregexprrr[contentseqnewdtypeoutputs r/r#r#nsD|F 4 yyvv!!&&tTH&E%*HHUOE ;; BC C))+ gu %*VS*AV_Fvw'ZZ'FnnW% z#a&%0xxekk!n 56HXXc2F FLXXc/F  JJL 6 JJL s D$F F _zf%i)rr0c#Oi|Pt||fid|d|d|d|d|d|d|d |d | d | d | d | d| d|d|d|d|d|d|d|d|d|d|St|||r td|dkr td|rddlm}m}|xsi}t |tstdt|z|dk(rd}d }nd!}t |tjrtj|}t |trBtjj j#|d"|#}t%j&|}n|}t%j(|} t+|}|5t-||||&}!t/| | || '}" t1|D] Ot3|d}#|#sMt5t3||}$| d ur)|'||$vr#d(j7|$j9|dd}$|!|$}#|#sM| d ur|#djA}%||%|vr|#d=| - | j9d-D&cgc]}&|&jA} }&tG| xs|#}'| d ur0|"|#D&cgc]}&t|&jAc}&} d(}$nItI| r4|"| j9d-D&cgc]}&|&jAc}&} n | r|"| } |tK||| | | || .}| tE| } | rtM| D]<\O}(tI|(r| jO|(| O<&|(dks,|(tG|#z| O<>|VtG||'kDrH|jP})tjR| D&cgc]}&|)|& c}&}tE|jT} n<| :tG| |'kDr,| D&cgc]}&| |& } }&n| |tE|jT} |xsd/}*t |*tVr|*jYd0}*t1|'D&cgc]}&d(g}}&t |*tr|*j[D]\}+},tI|+r | jO|+}+| r | jO|+}+t |,tDt\fr|,D&cgc] }&t|&},}&n t|,g},|+|D]}-|-j_|,||+j_|,nt |*tDt\fr6ta|*|D]&\}.}/t|.}.|.|/vs|/jc|.(n\t |*tr*|*j9d-}0|D]}/|/j_|0n"|D]}/|/j_t|*g|}1|1g}1dg|'z}t |1trO|1j[D];\}+},tI|+r | jO|+}+| r | jO|+}+|,||+<=n8t |1tDt\frtG|1}2|2|'kr|1|d|2n |1d|'}n|1g|'z}|+ta||D-3cgc]\}-}3ted|-|31}}-}3nztg|d 2}4tG|4dkDr2ta|4||}5|5D6-3cgc]\}6}-}3te|6d |-|33}}-}6}3n-ta||}5|5D-3cgc]\}-}3te|d |-|33}}-}3g}7|j[D]\}8}9tI|8r | jO|8}8|8On| r | jO|8On|8OtG$r|#|8}:nd}:|9tVurth};n|rd4}|rg}?|?jb}@g}A|Ajb}BtMtqjr$g|D]\O}C|!|C}DtG|D}E|Edk(r| r | D&cgc]}&D|& }D}&nE|'k7rBO|zdzEfK|>t]D|r"@t]d7taD|DtG|=|k(snddd|CtM|D]5\O}F=DGcgc]}GtwO|G}H}G FjyH7tGA}K|KdkDrtG=Kz|z }Ld='d>}M|dkDr1tGAD&cgc]}&|&dL|zkDr|&c}&}NAdK|Nz }A||Nz}ADOPcgc] \}O}PM|O|Pfz}I}O}PtG|IrLIjdd?d@j7|I}I|r tIt=j>Itd+,|dkDr=d| }=|r?d| }?|r`tEtatM|DO9Qcgc]7\}O}9t}tw|O=DQcgc]}Q|9j|Qc}Q9c}Q}9}O}=n_tEtatM|DO9Qcgc]7\}O}9t}tw|O=DQcgc]}Q|9j|Qc}Q9c}Q}9}O}=|=}R||D9cgc]}9|9j}S}9tM|SDOTcgc]\}O}T|Ttjk(rOc}T}Oi|rhirft=j>dAtjjd+,ifdB}U RDVcgc] }VU|V }R}ViD]OtjSO< Sj}WtM|SD]E\O}Xtj|Xtjs+tOfdCRD}YX|YfWO<G| ta|SDZ[chc]\}Z}[|Zjr[}\}Z}[tG|\dk(r \\}]|]t}_}^ntMWDO6cgc] \}O}6||Oz|6f}^}O}6|rbtMWDO6cgc]\}O}6||Oztf}_}O}6n;tEta| W}^tEta| tgtG|Wz}_tjR^D}`|rMtj?_D}an4| r|jT| |_*tG4dkDrdEdF|4Dvr.t|r tdGtjR|D}`n8tjR|4D&cgc]}&d(|&fc}&D}=|=j|}`|rtj?tjR|4Dbcgc] }bd(tf c}bD}c|}_|cj|_}anD|rd }dg})tM|D9cgc]}9|9jc}9D]|\O}eO|vr`de|jk(z}dtj|etjretOfdHRDf}e|)jcd(efj|)jcd(|f~ds9tG|)dkDrtjR|)}ntjRe}tjR|}`|rI|jT |jTD&cgc] }&|&tf }_}&nt}_tj?_D}a`jRjT} |rT| rRta| |D]C\}f}9|9jD&cgc]}&|&d(k7r|9|&}}&|D]}gafxx`|f|gk(zcc<E|r`j}`a|`_Ut`|I}`|r7| `jStG| dk(r`| dS| Dhcgc]}h`|h c}hS`S#t$r} td$t|d%| d} ~ wwxYw#t:$r#d(}$g}#t=j>d)|d*d+,Y wxYwcc}&w#tB$r# tE| } n#t$r| g} YnwxYwY wxYwcc}&wcc}&wcc}&wcc}&wcc}&w#t$rY wxYw#t$rY wxYwcc}&w#t$rY wxYw#t$rY wxYwcc}3}-wcc}3}-}6wcc}3}-w#t$rY wxYw#t$rY wxYwcc}&w#tt$rBO|zdzEfYwxYw#1swYQxYwcc}Gw#tz$rvd8Od9}It}twO|=}HtM|HD]I\}8}. Fj|.#ttf$r |8dz|z}JId:|Jd;|.d<z }It|IwxYwYwxYwcc}&wcc}P}Owcc}Qwcc}Q}9}Owcc}Qwcc}Q}9}Owcc}9wcc}T}Owcc}Vw#t$rY{wxYwcc}[}Zwcc}6}Owcc}6}Owcc}&wcc}bwcc}9wcc}&wcc}&wcc}hw)Ja Load data from a text file, with missing values handled as specified. Each line past the first `skip_header` lines is split at the `delimiter` character, and characters following the `comments` character are discarded. Parameters ---------- fname : file, str, pathlib.Path, list of str, generator File, filename, list, or generator to read. If the filename extension is ``.gz`` or ``.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 : dtype, optional Data type of the resulting array. If None, the dtypes will be determined by the contents of each column, individually. comments : str, optional The character used to indicate the start of a comment. All the characters occurring on a line after a comment are discarded. delimiter : str, int, or sequence, optional The string used to separate values. By default, any consecutive whitespaces act as delimiter. An integer or sequence of integers can also be provided as width(s) of each field. skiprows : int, optional `skiprows` was removed in numpy 1.10. Please use `skip_header` instead. skip_header : int, optional The number of lines to skip at the beginning of the file. skip_footer : int, optional The number of lines to skip at the end of the file. converters : variable, optional The set of functions that convert the data of a column to a value. The converters can also be used to provide a default value for missing data: ``converters = {3: lambda s: float(s or 0)}``. missing : variable, optional `missing` was removed in numpy 1.10. Please use `missing_values` instead. missing_values : variable, optional The set of strings corresponding to missing data. filling_values : variable, optional The set of values to be used as default when the data are missing. usecols : sequence, optional Which columns to read, with 0 being the first. For example, ``usecols = (1, 4, 5)`` will extract the 2nd, 5th and 6th columns. names : {None, True, str, sequence}, optional If `names` is True, the field names are read from the first line after the first `skip_header` lines. This line can optionally be preceded by a comment delimiter. Any content before the comment delimiter is discarded. If `names` is a sequence or a single-string of comma-separated names, the names will be used to define the field names in a structured dtype. If `names` is None, the names of the dtype fields will be used, if any. excludelist : sequence, optional A list of names to exclude. This list is appended to the default list ['return','file','print']. Excluded names are appended with an underscore: for example, `file` would become `file_`. deletechars : str, optional A string combining invalid characters that must be deleted from the names. defaultfmt : str, optional A format used to define default field names, such as "f%i" or "f_%02i". autostrip : bool, optional Whether to automatically strip white spaces from the variables. replace_space : char, optional Character(s) used in replacement of white spaces in the variable names. By default, use a '_'. case_sensitive : {True, False, 'upper', 'lower'}, optional If True, field names are case sensitive. If False or 'upper', field names are converted to upper case. If 'lower', field names are converted to lower case. unpack : bool, optional If True, the returned array is transposed, so that arguments may be unpacked using ``x, y, z = genfromtxt(...)``. When used with a structured data-type, arrays are returned for each field. Default is False. usemask : bool, optional If True, return a masked array. If False, return a regular array. loose : bool, optional If True, do not raise errors for invalid values. invalid_raise : bool, optional If True, an exception is raised if an inconsistency is detected in the number of columns. If False, a warning is emitted and the offending lines are skipped. max_rows : int, optional The maximum number of rows to read. Must not be used with skip_footer at the same time. If given, the value must be at least 1. Default is to read the entire file. encoding : str, optional Encoding used to decode the inputfile. Does not apply when `fname` is a file object. The special value 'bytes' enables backward compatibility workarounds that ensure that you receive byte arrays when 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'. .. versionchanged:: 2.0 Before NumPy 2, the default was ``'bytes'`` for Python 2 compatibility. The default is now ``None``. ndmin : int, optional Same parameter as `loadtxt` .. versionadded:: 1.23.0 ${ARRAY_FUNCTION_LIKE} .. versionadded:: 1.20.0 Returns ------- out : ndarray Data read from the text file. If `usemask` is True, this is a masked array. See Also -------- numpy.loadtxt : equivalent function when no data is missing. Notes ----- * When spaces are used as delimiters, or when no delimiter has been given as input, there should not be any missing data between two fields. * When variables are named (either by a flexible dtype or with a `names` sequence), there must not be any header in the file (else a ValueError exception is raised). * Individual values are not stripped of spaces by default. When using a custom converter, make sure the function does remove spaces. * Custom converters may receive unexpected values due to dtype discovery. References ---------- .. [1] NumPy User Guide, section `I/O with NumPy `_. Examples -------- >>> from io import StringIO >>> import numpy as np Comma delimited file with mixed dtype >>> s = StringIO("1,1.3,abcde") >>> data = np.genfromtxt(s, dtype=[('myint','i8'),('myfloat','f8'), ... ('mystring','S5')], delimiter=",") >>> data array((1, 1.3, b'abcde'), dtype=[('myint', '>> _ = s.seek(0) # needed for StringIO example only >>> data = np.genfromtxt(s, dtype=None, ... names = ['myint','myfloat','mystring'], delimiter=",") >>> data array((1, 1.3, 'abcde'), dtype=[('myint', '>> _ = s.seek(0) >>> data = np.genfromtxt(s, dtype="i8,f8,S5", ... names=['myint','myfloat','mystring'], delimiter=",") >>> data array((1, 1.3, b'abcde'), dtype=[('myint', '>> s = StringIO("11.3abcde") >>> data = np.genfromtxt(s, dtype=None, names=['intvar','fltvar','strvar'], ... delimiter=[1,3,5]) >>> data array((1, 1.3, 'abcde'), dtype=[('intvar', '>> f = StringIO(''' ... text,# of chars ... hello world,11 ... numpy,5''') >>> np.genfromtxt(f, dtype='S12,S12', delimiter=',') array([(b'text', b''), (b'hello world', b'11'), (b'numpy', b'5')], dtype=[('f0', 'S12'), ('f1', 'S12')]) Nrrr skip_header skip_footerrmissing_valuesfilling_valuesrr$ excludelist deletechars replace_space autostripcase_sensitive defaultfmtrusemaskloose invalid_raiserrrzPThe keywords 'skip_footer' and 'max_rows' can not be specified at the same time.r z'max_rows' must be at least 1.r) MaskedArraymake_mask_descrzNThe input argument 'converter' should be a valid dictionary (got '%s' instead)r}TFr rz\fname must be a string, a filehandle, a sequence of strings, or an iterator of strings. Got r)rrryr)rvrwrzrxr zgenfromtxt: Empty input file: "rrrr)r{r$rvrwrzrxrBr)rtr) flatten_base)lockedrtrcbt|tur||S||jdSNr)rr}rH)r5convs r/ tobytes_firstz!genfromtxt..tobytes_firsts+Aw%'#Aw 233r1)r)r testing_valuerrtc3FK|]\}}|j|vywr))strip).0rFms r/ zgenfromtxt..s(&J+1Aq'(ggi1n&Js!z Converter #z# is locked and cannot be upgraded: z(occurred line #z for value 'rSz( Line #%i (got %i columns instead of )zSome errors were detected !rQzReading unicode strings without specifying the encoding argument is deprecated. Set the encoding, use None for the system default.clt|}D]}||jd||<t|Sr)r:rHr)row_tupr`r strcolidxs r/encode_unicode_colsz'genfromtxt..encode_unicode_colsE s;7m"5A V]]84CF5Sz!r1c3:K|]}t|ywr)rurr`rs r/rzgenfromtxt..W s:cc#a&k:rfOc34K|]}|jywr))char)rrps r/rzgenfromtxt..y s2!qvv2sz4Nested fields involving objects are not supported...c3:K|]}t|ywr)rrs r/rzgenfromtxt.. s/LCF /Lrr)X_genfromtxt_with_likerrnumpy.marrrrYrrrGrrHrrrrryrrrrrrrrangenextrrr StopIterationrrrr6r:rurrrrdescrrr$r}rrrrXrZrrrr functoolspartialr\ itertoolschain IndexErrorr iterupgradermapupgraderinsertr _loose_call _strict_callstr_ exceptionsVisibleDeprecationWarningbytes_UnicodeEncodeErrorcopy issubdtype charactermax_checkedboolrjrNotImplementedErrorviewrt_maskrr)jrrrrrrrsrrtrurr$rvrwrxryrzr{rr|r}r~rrrr0rruser_convertersrr`fid_ctxfhdr split_linevalidate_names first_values first_linefvalrpnbcolscurrentruser_missing_valuesr8rmissrentry user_valueuser_filling_valuesnfill dtype_flatzipitr, uc_updaterrr user_convrrowsappend_to_rowsmasksappend_to_masksinvalidappend_to_invalidrrnbvalues converter_mcurrent_columnerrmsg line_number nbinvalidnbrowstemplatenbinvalid_skippedrnb_rr( column_typesrFrrsized_column_typescol_typen_charsrc_typebase uniform_typeddtypemdtypero outputmasktrowmasks ishomogeneousttypercmvalr-rsj ` @r/rrsP $ %  $  /7  CL  #  1<  "  3A  *  4;  CH  $  2=  (  4=  *  7A    $+  38  (  3;  FN    &e, 23 3 a<=> >9 &BO ot , !#'#8 9: :7%% % %ff  %%eTH%E$$S)((-3i a!I,5J &;3>6D5BD  ;' S   L")$s)X> TM(<:-GGJ$4$4X$>qr$BC#)*5 # D=?((*D#8#$Q   *.5mmC.@A1779AA W, - D="L#IqC N#IJEJ U #"u{{37G#H!AGGI#HIE "5)E  u5+6+6.<-: "J (E %LL' ( +S 1,2237J' ) Z( )( 9 c"5678 9 -  &"$ & )4 01779 * c"3'!#kk#. %mmC0'*s#! *$+dE] ;'(AV %8r"!4Wf!=22V;N = %($G T4 T4HJ 'u4@J:"JG 7< ==#32tT .b59=A6:<= =NN; 38 9#/4 .e59=A6:<9 9  (..0' -IQq! AAA a(A : ,Q $ u}#  4&--m$G  qM 4/<)7):0>q0A ! D   a^ ,O' -R y) E#llO#NN#9??J>3#GH IQ%F6{H1}189AfQi9F9V#!1{?Q#6"AB 5= )&J589G6I&J!JK4yH$/ UaH  }' 3 5NQ :>?BmjmB/?N? 5%%n5 5 G I1}TY&4=fXQG ? #%E1()!v /C(C&'%E!F Av::D4yA~ $ $0$*33E)FH%q"&>2.HH-67I-JL")1b *A~t4LFL#e%789F#edVc2D.E%EFGF$f- %v6J U[[,EK z?Q  2z22$U+-NPP XXd%8Fxxj,Ib!W,IJ5)88z*J!B:*J!KM)/%]]62  $  )*L499*L M2HAuO+%%5::*=> == =%*C/Lt/L,L$ME b%[1 b%[12%5zA~ "!#XXdE*F;;*16=Aq$i=F=!FXXe6: LL  E5z2 ;LT4/3/B/B*!!"b#1g*N*& ;4 VD\T%9:  ; ; [)! "6 7F =88O Z1_%(# #055eF5M5 5 Mg  ..25k]) E  8 JL MM1%:q    $B! **"7mG *&kG* *$J$I0"=47&! !&0P&! !&&=9" "p:!%q;':H&EFiaaL @& 5&qc)LM!$Z]D!9"+N";5JQ5!))%0*J75&'!ek&9 $4[MeWTV"WW,V4455 5$%E*,L:M::&$>%  HL2-J +K+M*>*(6s ~(ACA+~/4"AC#*#AC A@ <*AC&A@ =A+AC)AAC+ A@ 71AC( A@!4AAC A@&3ACA@+ACA@;'ACAA A8AC B-AC:AA ACAA AAC0AA02AC:AA6 AC*AA=&AC*AB=ACABC6AC AB( AB#AB(AAC6ACAC3AC;AE(AE!AE, AE'8AE,!AE8AE3AE80AE?AF0AF4AF AFAFAF%<AF+3 AF1 =AF6AF;AG1AG4 AG  ~,~''~,/(ACAC## A@- 98A@9 A@@A@@A@@A@@ AC@A@@AC@+ A@8@4AC@7A@8@8AC@; AAAACAAAAACA AAAACAAAAACA AA-A)ACA,AA-A-ACB ABB ACBABBACB AB BACBAB B ACB#AB(B(ACCACCACCACCACC5AEDAD"D!AED"/AE EAEEAEE'AE,E3AE8F AFF AFFAFc tjdtd|jdd|j dd}t |fi|}|rdd lm}|j|}|S|jtj}|S) a> Load ASCII data from a file and return it in a record array. If ``usemask=False`` a standard `recarray` is returned, if ``usemask=True`` a MaskedRecords array is returned. .. deprecated:: 2.0 Use `numpy.genfromtxt` instead. Parameters ---------- fname, kwargs : For a description of input parameters, see `genfromtxt`. See Also -------- numpy.genfromtxt : generic function Notes ----- By default, `dtype` is None, which means that the data-type of the output array will be determined from the data. zT`recfromtxt` is deprecated, use `numpy.genfromtxt` instead.(deprecated in NumPy 2.0)rrrNr|Fr MaskedRecords) rrr setdefaultrrnumpy.ma.mrecordsrrrrecarray)rrMr|rors r/ recfromtxtr s4 MM $   gt$jjE*G  ( (F3]+ MR[[) Mr1c ~tjdtd|jdd|jdd|jdd |jd d t |fi|}|j d d }|rddlm}|j|}|S|jtj}|S)a Load ASCII data stored in a comma-separated file. The returned array is a record array (if ``usemask=False``, see `recarray`) or a masked record array (if ``usemask=True``, see `ma.mrecords.MaskedRecords`). .. deprecated:: 2.0 Use `numpy.genfromtxt` with comma as `delimiter` instead. Parameters ---------- fname, kwargs : For a description of input parameters, see `genfromtxt`. See Also -------- numpy.genfromtxt : generic function to load ASCII data. Notes ----- By default, `dtype` is None, which means that the data-type of the output array will be determined from the data. zo`recfromcsv` is deprecated, use `numpy.genfromtxt` with comma as `delimiter` instead. (deprecated in NumPy 2.0)rrrzlowerr$TrrrNr|Frr) rrrrrrrrrrr)rrMror|rs r/ recfromcsvr s6 MM $   &0 gt$ k3' gt$  ( (FjjE*G3]+ MR[[) Mr1)NFTr)NN)TN)argument)NNNNNNN)z%.18e rQr r z# Nr))RrArrrrrGrrgrr*collections.abcrrr$r numpy._corernumpy._core._multiarray_umathrnumpy._core.multiarrayrrnumpy._core.overridesr r numpy._utilsr r r rrr _format_implr_iotoolsrrrrrrrrrrr__all__rarray_function_dispatchr'rNrPrrrr rr!rr"rrintrrrrr4r.floatrr3r<rr#rsorteddefaultdeletecharsrrrrrBr1r/r s #!=7J+#*      ,)++ %%g7/B/Bd 2 @$g@$@$F G?CyM.>yMyMx)*!%2;;PG+PGf15 *+$(\?,\?~<@ 56/3G>7G>T"JE s 08&"3cdaDU T~B GaedTM@DMM`/,.w7EI;?!% ,-GI/3d.dN G]]J G!C4!"4t776-*J*J#KL E$e4!D4k k k \2/1*=*Z0r1