B >> a = np.array([(1, 2.0), (1, 2.0)], dtype=[('x', int), ('y', float)]) >>> a array([(1, 2.0), (1, 2.0)], dtype=[('x', '>> a['x'] array([1, 1]) >>> a['y'] array([ 2., 2.]) Record arrays allow us to access fields as properties:: >>> ar = np.rec.array(a) >>> ar.x array([1, 1]) >>> ar.y array([ 2., 2.]) )divisionabsolute_importprint_functionN)numeric) numerictypes) isfileobjbyteslongrecordrecarray format_parser><=s|)blnBLNSrrrrrIicCsPg}xFtt|D]6}||||ddkr|||kr|||qW|S)z@Find duplication in a list, return a list of duplicated elementsrN)rangelenappend)listduprr!E/opt/alt/python37/lib64/python3.7/site-packages/numpy/core/records.pyfind_duplicateJs  r#c@s4eZdZdZd ddZdddZd d Zd d ZdS)r a Class to convert formats, names, titles description to a dtype. After constructing the format_parser object, the dtype attribute is the converted data-type: ``dtype = format_parser(formats, names, titles).dtype`` Attributes ---------- dtype : dtype The converted data-type. Parameters ---------- formats : str or list of str The format description, either specified as a string with comma-separated format descriptions in the form ``'f8, i4, a5'``, or a list of format description strings in the form ``['f8', 'i4', 'a5']``. names : str or list/tuple of str The field names, either specified as a comma-separated string in the form ``'col1, col2, col3'``, or as a list or tuple of strings in the form ``['col1', 'col2', 'col3']``. An empty list can be used, in that case default field names ('f0', 'f1', ...) are used. titles : sequence Sequence of title strings. An empty list can be used to leave titles out. aligned : bool, optional If True, align the fields by padding as the C-compiler would. Default is False. byteorder : str, optional If specified, all the fields will be changed to the provided byte-order. Otherwise, the default byte-order is used. For all available string specifiers, see `dtype.newbyteorder`. See Also -------- dtype, typename, sctype2char Examples -------- >>> np.format_parser(['f8', 'i4', 'a5'], ['col1', 'col2', 'col3'], ... ['T1', 'T2', 'T3']).dtype dtype([(('T1', 'col1'), '>> np.format_parser(['f8', 'i4', 'a5'], ['col1', 'col2', 'col3'], ... []).dtype dtype([('col1', '>> np.format_parser(['f8', 'i4', 'a5'], [], []).dtype dtype([('f0', 'sz/format_parser._parseFormats..csg|]}|dqS)rr!)r4r5)r6r!r"r7s) ValueError isinstancerrrjoinsbr(r6r+ _f_formats_offsets_nfields)r)r*r-r(keysr!)r6r"r$s     zformat_parser._parseFormatscCs|rXt|ttgkrn&t|tr,|d}ntdt|dd|d|jD|_ ng|_ |j ddt t |j |jD7_ t |j }|rt d||rdd|d|jD|_n g|_g}|jt |kr|jdg|jt |7_dS) zQconvert input field names into a list and assign to the _names attribute r2zillegal input names %scSsg|] }|qSr!)strip)r4rr!r!r"r7sz0format_parser._setfieldnames..NcSsg|] }d|qS)zf%dr!)r4rr!r!r"r7szDuplicate field names: %scSsg|] }|qSr!)r@)r4rr!r!r"r7s)typertupler9strsplit NameErrorreprr>_namesrrr#r8_titles)r)r+r,Z_dupr!r!r"r%s&    zformat_parser._setfieldnamescCsDt|j|j|j|jd}|dk r:t|d}||}||_dS)N)r+r*Zoffsetsr,r) r;r(rGr<r=rH_byteorderconvZ newbyteorderr')r)r.descrr!r!r"r&s   zformat_parser._createdescr)FN)r)__name__ __module__ __qualname____doc__r/r$r%r&r!r!r!r"r Ss :  $c@sHeZdZdZdZdZddZddZddZd d Zd d Zd dZ dS)r zEA data-type scalar that allows field access as attribute lookup. numpycCs|S)N)__str__)r)r!r!r"__repr__szrecord.__repr__cCs t|S)N)rCitem)r)r!r!r"rPszrecord.__str__cCs|dkrtj||Sytj||Stk r8YnXtj|dj}||d}|r|j|dd}y |j}Wntk r|SX|jr||j |jjfS|Std|dS)N)setfieldgetfieldr(r(r0z%'record' object has no attribute '%s') ntvoid__getattribute__AttributeErrorr6getrTr(view __class__)r)attr fielddictresobjZdtr!r!r"rWs&  zrecord.__getattribute__cCsx|dkrtd|tj|dj}||d}|rL|j|f|ddSt||drhtj|||Std|dS)N)rSrTr(zCannot set '%s' attributer(r0z%'record' object has no attribute '%s') rXrUrVrWr6rYrSgetattr __setattr__)r)r\valr]r^r!r!r"ras   zrecord.__setattr__cCs>tj||}t|tjr6|jjr6||j|jjfS|SdS)N)rUrV __getitem__r9r(r6rZr[)r)indxr_r!r!r"rc szrecord.__getitem__cCsV|jj}tdd|D}g}d|}x$|D]}|||t||fq,Wd|S)zPretty-print all fields.css|]}t|VqdS)N)r)r4namer!r!r" sz record.pprint..z %% %ds: %%s )r(r+maxrr`r:)r)r+maxlenZrowsfmtrer!r!r"pprints z record.pprintN) rKrLrMrNrQrPrWrarcrkr!r!r!r"r s c s\eZdZdZdZdZdddZd d Zd d Zd dZfddZddZ dddZ Z S)r a2Construct an ndarray that allows field access using attributes. Arrays may have a data-types containing fields, analogous to columns in a spread sheet. An example is ``[(x, int), (y, float)]``, where each entry in the array is a pair of ``(int, float)``. Normally, these attributes are accessed using dictionary lookups such as ``arr['x']`` and ``arr['y']``. Record arrays allow the fields to be accessed as members of the array, using ``arr.x`` and ``arr.y``. Parameters ---------- shape : tuple Shape of output array. dtype : data-type, optional The desired data-type. By default, the data-type is determined from `formats`, `names`, `titles`, `aligned` and `byteorder`. formats : list of data-types, optional A list containing the data-types for the different columns, e.g. ``['i4', 'f8', 'i4']``. `formats` does *not* support the new convention of using types directly, i.e. ``(int, float, int)``. Note that `formats` must be a list, not a tuple. Given that `formats` is somewhat limited, we recommend specifying `dtype` instead. names : tuple of str, optional The name of each column, e.g. ``('x', 'y', 'z')``. buf : buffer, optional By default, a new array is created of the given shape and data-type. If `buf` is specified and is an object exposing the buffer interface, the array will use the memory from the existing buffer. In this case, the `offset` and `strides` keywords are available. Other Parameters ---------------- titles : tuple of str, optional Aliases for column names. For example, if `names` were ``('x', 'y', 'z')`` and `titles` is ``('x_coordinate', 'y_coordinate', 'z_coordinate')``, then ``arr['x']`` is equivalent to both ``arr.x`` and ``arr.x_coordinate``. byteorder : {'<', '>', '='}, optional Byte-order for all fields. aligned : bool, optional Align the fields in memory as the C-compiler would. strides : tuple of ints, optional Buffer (`buf`) is interpreted according to these strides (strides define how many bytes each array element, row, column, etc. occupy in memory). offset : int, optional Start reading buffer (`buf`) from this offset onwards. order : {'C', 'F'}, optional Row-major (C-style) or column-major (Fortran-style) order. Returns ------- rec : recarray Empty array of the given shape and type. See Also -------- rec.fromrecords : Construct a record array from data. record : fundamental data-type for `recarray`. format_parser : determine a data-type from formats, names, titles. Notes ----- This constructor can be compared to ``empty``: it creates a new record array but does not fill it with data. To create a record array from data, use one of the following methods: 1. Create a standard ndarray and convert it to a record array, using ``arr.view(np.recarray)`` 2. Use the `buf` keyword. 3. Use `np.rec.fromrecords`. Examples -------- Create an array with two fields, ``x`` and ``y``: >>> x = np.array([(1.0, 2), (3.0, 4)], dtype=[('x', float), ('y', int)]) >>> x array([(1.0, 2), (3.0, 4)], dtype=[('x', '>> x['x'] array([ 1., 3.]) View the array as a record array: >>> x = x.view(np.recarray) >>> x.x array([ 1., 3.]) >>> x.y array([2, 4]) Create a new, empty record array: >>> np.recarray((2,), ... dtype=[('x', int), ('y', float), ('z', int)]) #doctest: +SKIP rec.array([(-1073741821, 1.2249118382103472e-301, 24547520), (3471280, 1.2134086255804012e-316, 0)], dtype=[('x', '\}}| |j} |jd|j| }||krtd|qWt|| }x&tt|D]}|||| |<q^W|S) aA create a record array from a (flat) list of arrays >>> x1=np.array([1,2,3,4]) >>> x2=np.array(['a','dd','xyz','12']) >>> x3=np.array([1.1,2,3,4]) >>> r = np.core.records.fromarrays([x1,x2,x3],names='a,b,c') >>> print(r[1]) (2, 'dd', 2.0) >>> x1[1]=34 >>> r.a array([1, 2, 3, 4]) cSsg|]}t|qSr!)r;Zasarray)r4xr!r!r"r7Cszfromarrays..Nrz*item in the array list must be an ndarray.r2z>mismatch between the number of fields and the number of arraysz array-shape mismatch in array %d)rsr9rrqr8rr(rCr:r;r+r rGr'r enumeratendimr r)Z arrayListr(rsr*r+r,r-r.r_rJrGZparsedZd0ZnnkZ testshape_arrayrr!r!r" fromarrays4sB          rc s<|dkrP|dkrPtj|tdfddtjdD}t|||||||dS|dk rhtt|f} nt|||||j } ytj|| d} Wnt k r|dks|dkrt |}t |t tfr|f}t |dkrtd t|| } x"t| jD]} t|| | | <qW| SX|dk r.| j|kr.|| _| t} | S) ad create a recarray from a list of records in text form The data in the same field can be heterogeneous, they will be promoted to the highest data type. This method is intended for creating smaller record arrays. If used to create large array without formats defined r=fromrecords([(2,3.,'abc')]*100000) it can be slow. If formats is None, then this will auto-detect formats. Use list of tuples rather than list of lists for faster processing. >>> r=np.core.records.fromrecords([(456,'dbe',1.2),(2,'de',1.3)], ... names='col1,col2,col3') >>> print(r[0]) (456, 'dbe', 1.2) >>> r.col1 array([456, 2]) >>> r.col2 array(['dbe', 'de'], dtype='|S3') >>> import pickle >>> print(pickle.loads(pickle.dumps(r))) [(456, 'dbe', 1.2) (2, 'de', 1.3)] N)r(cs"g|]}td|fqS).)r;arraytolist)r4r)r_r!r"r7szfromrecords..)r*rsr+r,r-r.rrzCan only deal with 1-d array.)r;rrvrrsrr(r r r'rwrr9rr r8r rrBrZ)ZrecListr(rsr*r+r,r-r.ZarrlistrJZretvalrrr^r!)r_r" fromrecordsus2     rc Cs|dkr|dkrtd|dk r,t|} nt|||||j} | j} |dks\|dks\|dkrlt||| }t|| ||d} | S)zM create a (read-only) record array from binary data contained in a stringNzMust have dtype= or formats=rr)rtro)r8r;r(r r'itemsizerr ) Z datastringr(rsror*r+r,r-r.rJrrr!r!r" fromstrings rcCsPy |}Wn&tk r2tj|j|SXt|}|j|}|S)N) filenorXospathgetsizeretellfstatst_size)fdfnstrr!r!r"get_remaining_sizes  rc Cs0|dks|dkrd}nt|ttfr*|f}d} t|trFd} t|d}|dkrZ||dt|} |dk rvt|} nt |||||j } | j } t | } | | }|dkrt|}| | ||d<t|}t | } | | }|| krtdt|| }||j}||krtd| r,||S) amCreate an array from binary file data If file is a string then that file is opened, else it is assumed to be a file object. The file object must support random access (i.e. it must have tell and seek methods). >>> from tempfile import TemporaryFile >>> a = np.empty(10,dtype='f8,i4,a5') >>> a[5] = (0.5,10,'abcde') >>> >>> fd=TemporaryFile() >>> a = a.newbyteorder('<') >>> a.tofile(fd) >>> >>> fd.seek(0) >>> r=np.core.records.fromfile(fd, formats='f8,i4,a5', shape=10, ... byteorder='<') >>> print(r[5]) (0.5, 10, 'abcde') >>> r.shape (10,) Nr)rrrbrz:Not enough bytes left in file for specified shape and typez%Didn't read as many bytes as expected)r9rr rCopenseekrr;r(r r'rrZprodrindexrBr8r readintodataIOErrorclose)rr(rsror*r+r,r-r.rerrJrZ shapeprodZ shapesizenbytesrZ nbytesreadr!r!r"fromfilesB       rTc Cs t|tdtfst|r2|dkr2|dkr2tdi} |dk rJt|}n,|dk rft||||| j}n||||| d} |dkr|dkrtdt |||||dSt|t rt ||f||d| St|t t frt|dt t frt|f||d| St|f||d| Snt|t rZ|dk rD|j|krD||} n|} | rV| } | St|rtt||||d St|tr|dk r|j|kr||} n|} | r| } | t St|d d} | dkst| tstd t|}|dk r|j|kr||}|t SdS) z=Construct a record array from a wide-variety of objects. NzIMust define formats (or dtype) if object is None, string, or an open file)r*r+r,r-r.z"Must define a shape if obj is None)rtrorp)rsror)r(rs)r(rsroZ__array_interface__zUnknown input type)r9rArCrr8r;r(r r'r r rrrBrrrZcopyrrqr`dictr)r_r(rsrorpr*r+r,r-r.rkwdsnewZ interfacer!r!r"rs^            r)NNNNNFN)NNNNNFN)NNrNNNFN)NNrNNNFN) NNrNNNNFNT) rNZ __future__rrrr{rr1rr;rrUZ numpy.compatrr r __all__rqrIZtypeDictZnumfmtr#r rVr r rrrrrrr!r!r!r"$sR    S  @ >   D