K ijdZddlZddlZddlmZddlmcmZddl m Z ddl m Z gdZ dZe edZdZd Zd Zd Zd7d Zd7d Zd8dZdZdZd9dZd:dZd;dZ ddZ&d;dZ'e e'd;d Z(d8d!Z)e e)d?d"Z*d@d#Z+d$Z, dAd%Z-e e-dBd&Z. dCd'Z/e e/ dDd(Z0d)Z1e e1d*Z2d;d+Z3e e3dEd,Z4d-Z5e e5d.Z6 d[ y)Kz Collection of utilities to manipulate structured arrays. Most of these functions were initially implemented by John Hunter for matplotlib. They have been rewritten and extended for convenience. N)array_function_dispatch)_is_string_like) append_fieldsapply_along_fieldsassign_fields_by_name drop_fieldsfind_duplicates flatten_descrget_fieldstructure get_namesget_names_flatjoin_by merge_arraysrec_append_fieldsrec_drop_fieldsrec_joinrecursive_fill_fields rename_fields repack_fieldsrequire_fields stack_arraysstructured_to_unstructuredunstructured_to_structuredc ||fSN)inputoutputs \/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/numpy/lib/recfunctions.py!_recursive_fill_fields_dispatcherr s 6?c|j}|jD]?} ||}|jjt|||/|||dt |A|S#t$rYOwxYw)a Fills fields from output with fields from input, with support for nested structures. Parameters ---------- input : ndarray Input array. output : ndarray Output array. Notes ----- * `output` should be at least the same size as `input` Examples -------- >>> import numpy as np >>> from numpy.lib import recfunctions as rfn >>> a = np.array([(1, 10.), (2, 20.)], dtype=[('A', np.int64), ('B', np.float64)]) >>> b = np.zeros((3,), dtype=a.dtype) >>> rfn.recursive_fill_fields(a, b) array([(1, 10.), (2, 20.), (0, 0.)], dtype=[('A', '>> import numpy as np >>> dt = np.dtype([(('a', 'A'), np.int64), ('b', np.double, 3)]) >>> dt.descr [(('a', 'A'), '>> _get_fieldspec(dt) [(('a', 'A'), dtype('int64')), ('b', dtype(('z!_get_fieldspec.._sE4d+,Esr)r$r&)r#r-r/fs` r_get_fieldspecr3Gsl( {{U }EE" aVq[TqtTlAaD 9   s&Ac g}|j}|D]J}||}|j&|j|tt|f:|j|Lt|S)ab Returns the field names of the input datatype as a tuple. Input datatype must have fields otherwise error is raised. Parameters ---------- adtype : dtype Input datatype Examples -------- >>> import numpy as np >>> from numpy.lib import recfunctions as rfn >>> rfn.get_names(np.empty((1,), dtype=[('A', int)]).dtype) ('A',) >>> rfn.get_names(np.empty((1,), dtype=[('A',int), ('B', float)]).dtype) ('A', 'B') >>> adtype = np.dtype([('a', int), ('b', [('ba', int), ('bb', int)])]) >>> rfn.get_names(adtype) ('a', ('b', ('ba', 'bb'))) )r$appendtupler adtype listnamesr$r/r)s rr r gsl,I LLE#, == $   dE)G*<$=> ?   T " #  r!cg}|j}|D]?}|j|||}|j&|jt|At |S)a Returns the field names of the input datatype as a tuple. Input datatype must have fields otherwise error is raised. Nested structure are flattened beforehand. Parameters ---------- adtype : dtype Input datatype Examples -------- >>> import numpy as np >>> from numpy.lib import recfunctions as rfn >>> rfn.get_names_flat(np.empty((1,), dtype=[('A', int)]).dtype) is None False >>> rfn.get_names_flat(np.empty((1,), dtype=[('A',int), ('B', str)]).dtype) ('A', 'B') >>> adtype = np.dtype([('a', int), ('b', [('ba', int), ('bb', int)])]) >>> rfn.get_names_flat(adtype) ('a', 'b', 'ba', 'bb') )r$r5extendr r6r7s rr r sb.I LLE6, == $   ^G4 5 6  r!c|j}|d|ffSg}|D]N}|j|\}}|j|jt|<|j ||fPt |S)a_ Flatten a structured data-type description. Examples -------- >>> import numpy as np >>> from numpy.lib import recfunctions as rfn >>> ndtype = np.dtype([('a', '>> rfn.flatten_descr(ndtype) (('a', dtype('int32')), ('ba', dtype('float64')), ('bb', dtype('int32'))) r+)r$r-r;r r5r6)ndtyper$descrr(typ_s rr r s{ LLE }V  +E}}U+HS!yy$ ]3/0 eS\*  + U|r!cVg}|r,|D]&}|jt|j(ne|D]`}|j}|j3t |jdk(r|jt |N|j d|fbtj|S)Nr+)r;r r#r$r&r3r5np) seqarraysflattenr'ar)s r _zip_dtyperGsH 4A OOM!''2 3 4 /AggG}}(S-?1-Dw 78W .  / 88H r!c0t||jS)z Combine the dtype description of a series of arrays. Parameters ---------- seqarrays : sequence of arrays Sequence of arrays flatten : {boolean}, optional Whether to collapse nested descriptions. rE)rGr>)rDrEs r _zip_descrrJs i 1 7 77r!c.|i}|j}|D]}||}|j+|r|g||<ng||<|jt|||?t|j |gxsg}|r|j |n|r|g}|xsg||<|S)a} Returns a dictionary with fields indexing lists of their parent fields. This function is used to simplify access to fields nested in other fields. Parameters ---------- adtype : np.dtype Input datatype lastname : optional Last processed field name (used internally during recursion). parents : dictionary Dictionary of parent fields (used internally during recursion). Examples -------- >>> import numpy as np >>> from numpy.lib import recfunctions as rfn >>> ndtype = np.dtype([('A', int), ... ('B', [('BA', int), ... ('BB', [('BBA', int), ('BBB', int)])])]) >>> rfn.get_fieldstructure(ndtype) ... # XXX: possible regression, order of BBA and BBB is swapped {'A': [], 'B': [], 'BA': ['B'], 'BB': ['B'], 'BBA': ['B', 'BB'], 'BBB': ['B', 'BB']} )r$updater listgetr5)r8lastnameparentsr$r/r) lastparents rr r s6 LLE-, == $!)  " NN-gtWE Fgkk(B7=2>J!!(+&\ &,"GDM- Nr!c#K|D]=}t|tjrtt |Ed{:|?y7 w)zu Returns an iterator of concatenated fields from a sequence of arrays, collapsing any nested structure. N) isinstancerCvoid_izip_fields_flatr6iterableelements rrUrUs?  grww '(w8 8 8M  8s7AA Ac#K|D]{}t|dr$t|tst|Ed{3t|tj r+t t|dk(rt|Ed{x|}y7Q7w)zP Returns an iterator of concatenated fields from a sequence of arrays. __iter__NrB)hasattrrSstr _izip_fieldsrCrTr&r6rVs rr]r]su  GZ (w,#G, , ,  )c%..AQ.F#G, , ,M - -s"0BBAB7B8 BBc#K|rt}nt}tj|d|iD]}t ||yw)a* Returns an iterator of concatenated items from a sequence of arrays. Parameters ---------- seqarrays : sequence of arrays Sequence of arrays. fill_value : {None, integer} Value used to pad shorter iterables. flatten : {True, False}, Whether to fillvalueN)rUr] itertools zip_longestr6)rD fill_valuerEzipfunctups r _izip_recordsre/sC#$$iF:F"GCL!!"s>Act|tjsd}|r#|r|jtj }|Stj |}|r|jtj}|S)z Private function: return a recarray, a ndarray, a MaskedArray or a MaskedRecords depending on the input parameters F) rSma MaskedArrayviewmrec MaskedRecordsfilledrCrecarray)rusemask asrecarrays r _fix_outputrpGsb fbnn - [[!3!34F M6" [[-F Mr!c|jj}|j|j|j}}}|xsij D]\}}||vs |||<|||||<|S)zp Update the fill_value and masked data of `output` from the default given in a dictionary defaults. )r#r$datamaskrbitems)rdefaultsr$rrrsrbkvs r _fix_defaultsrxXsw LL  E & V[[&:K:K4T>r((*!A :JqM DGDG ! Mr!c|Srr)rDrbrErnros r_merge_arrays_dispatcherrzfs r!c $ t|dk(rtj|d}t|tjtj fr|j }|jtj d|fg}|rt|fd|k(rl|j}|r$|rtj}n4tj}n#|rtj}ntj}|j||S|f}n"|Dcgc]}tj|}}t!d|D}t#|} t||} g} g} |rt%||D]`\} }| |z }| jj'}tj(| j}|rtj*|| j }t|tjtj frvt|j dk(r|j-d}d}nHtj.|| j d }tj0d |j }nd}d}| j3t5j6||g|z| j3t5j6|g|zct!t9| |}tj.tj:|| | t=t9| | }|r|jtj}|St%||D]\} }| |z }| jj'}|rtj*|| j }t|tjtj frQt|j dk(r|j-d}n%tj.|| j d }nd}| j3t5j6||g|ztj:t!t9| || | }|r|jtj}|Scc}w)am Merge arrays field by field. Parameters ---------- seqarrays : sequence of ndarrays Sequence of arrays fill_value : {float}, optional Filling value used to pad missing data on the shorter arrays. flatten : {False, True}, optional Whether to collapse nested fields. usemask : {False, True}, optional Whether to return a masked array or not. asrecarray : {False, True}, optional Whether to return a recarray (MaskedRecords) or not. Examples -------- >>> import numpy as np >>> from numpy.lib import recfunctions as rfn >>> rfn.merge_arrays((np.array([1, 2]), np.array([10., 20., 30.]))) array([( 1, 10.), ( 2, 20.), (-1, 30.)], dtype=[('f0', '>> rfn.merge_arrays((np.array([1, 2], dtype=np.int64), ... np.array([10., 20., 30.])), usemask=False) array([(1, 10.0), (2, 20.0), (-1, 30.0)], dtype=[('f0', '>> rfn.merge_arrays((np.array([1, 2]).view([('a', np.int64)]), ... np.array([10., 20., 30.])), ... usemask=False, asrecarray=True) rec.array([( 1, 10.), ( 2, 20.), (-1, 30.)], dtype=[('a', '.s,Q!&&,s)r#ndmin)rBr#)r#count)rs)r&rC asanyarrayrSndarrayrTr#r$rGravelrjrkrgrhrmrir6maxzip __array__ getmaskarray_check_fill_valueitemarrayonesr5r`chainrefromiterrM)rDrbrErnroseqdtypeseqtype_msizes maxlengthr'seqdataseqmaskrFn nbmissingrrrsfvalfmskrs rrrksd I!MM)A,/ )bjj"''23?? >> !xx"h 01H*i\4@HL!)I"00G nnG++**>>w>? ?" I2;;2R]]2&; ; ,), ,EE I)W5HGG)U+ FFQ"QI779&&(D??1%++-D--j!''BdRZZ$9:4::!+#yy{1~#!xxAGG1E!wwt4::> NN9??4$)1CD E NN9??4$)1CD E) F,]7G<="++d()L#M'7$KLN [[!3!34F* M%)U+ FFQ"QI779&&(D--j!''BdRZZ$9:4::!+#yy{1~!xxAGG1E NN9??4$)1CD E FU='#JK#+9> [[-F Mu>> import numpy as np >>> from numpy.lib import recfunctions as rfn >>> a = np.array([(1, (2, 3.0)), (4, (5, 6.0))], ... dtype=[('a', np.int64), ('b', [('ba', np.double), ('bb', np.int64)])]) >>> rfn.drop_fields(a, 'a') array([((2., 3),), ((5., 6),)], dtype=[('b', [('ba', '>> rfn.drop_fields(a, 'ba') array([(1, (3,)), (4, (6,))], dtype=[('a', '>> rfn.drop_fields(a, ['ba', 'bb']) array([(1,), (4,)], dtype=[('a', ' _drop_descrs rrz drop_fields.._drop_descr st  1DTlGz!}}(#GZ8OOT5M2w0 1r!rrnro)rsetr#rCemptyshaperrp)rrrnror'rrs @rrrsdFz" \ _  4::z2H XXdjj 1F "4 0F vw: FFr!c|Dcgc]}||j|f}}tj|j|}t ||}t |||Scc}w)a Return a new array keeping only the fields in `keep_names`, and preserving the order of those fields. Parameters ---------- base : array Input array keep_names : string or sequence String or sequence of strings corresponding to the names of the fields to keep. Order of the names will be preserved. usemask : {False, True}, optional Whether to return a masked array or not. asrecarray : string or sequence, optional Whether to return a recarray or a mrecarray (`asrecarray=True`) or a plain ndarray or masked array with flexible dtype. The default is False. rr)r#rCrrrrp)r keep_namesrnrorr'rs r _keep_fieldsr6sX&-77qDJJqM"7H7 XXdjj 1F "4 0F vw: FF8sAc|fSrrrrs r_rec_drop_fields_dispatcherrOrr!c t||ddS)zK Returns a new numpy.recarray with fields in `drop_names` dropped. FTr)rrs rrrSs tZ4 HHr!c|fSrr)r namemappers r_rename_fields_dispatcherr[rr!cVfd|j|}|j|S)a Rename the fields from a flexible-datatype ndarray or recarray. Nested fields are supported. Parameters ---------- base : ndarray Input array whose fields must be modified. namemapper : dictionary Dictionary mapping old field names to their new version. Examples -------- >>> import numpy as np >>> from numpy.lib import recfunctions as rfn >>> a = np.array([(1, (2, [3.0, 30.])), (4, (5, [6.0, 60.]))], ... dtype=[('a', int),('b', [('ba', float), ('bb', (float, 2))])]) >>> rfn.rename_fields(a, {'a':'A', 'bb':'BB'}) array([(1, (2., [ 3., 30.])), (4, (5., [ 6., 60.]))], dtype=[('A', '._recursive_rename_fieldsxstLL 4D nnT40GTlG}}(6w KL' 23 4r!)r#ri)rrr'rs @rrr_s)2 ( J?H 99X r!c#,K||Ed{y7wrr)rr$rrdtypesrbrnros r_append_fields_dispatcherrs JOO c Pt|ttfr$t|t|k7r#d}t |t|t r|g}|g}|`|Dcgc]}t j|dd}}t||D cgc]#\} }|j| |jfg%}} }nt|ttfs|g}t|t|k7r*t|dk(r|t|z}n d}t |t|||D cgc]1\}} } t j|dd| j| | fg3}} }} t|||}t|dkDrt|d|| }n|j}tjtt|t|t!|jt!|jz } t#|| } t#|| } t%| || Scc}wcc}} wcc} } }w) a  Add new fields to an existing array. The names of the fields are given with the `names` arguments, the corresponding values with the `data` arguments. If a single field is appended, `names`, `data` and `dtypes` do not have to be lists but just values. Parameters ---------- base : array Input array to extend. names : string, sequence String or sequence of strings corresponding to the names of the new fields. data : array or sequence of arrays Array or sequence of arrays storing the fields to add to the base. dtypes : sequence of datatypes, optional Datatype or sequence of datatypes. If None, the datatypes are estimated from the `data`. fill_value : {float}, optional Filling value used to pad missing data on the shorter arrays. usemask : {False, True}, optional Whether to return a masked array or not. asrecarray : {False, True}, optional Whether to return a recarray (MaskedRecords) or not. z7The number of arrays does not match the number of namesNT)copysubokrBz5The dtypes argument must be None, a dtype, or a list.)rrr#)rnrb)rErnrbrr)rSr6rMr&r%r\rCrrrir#rpoprg masked_allrr3rrp) rr$rrrrbrnromsgrFr/rdrs rrrs@%%' u:T "KCS/ ! E3  x ~<@AqT2AA;>ud;KLitQqww()LL&5$-0ZF t9F #6{a#d)+M o%!$T5&!9;;Q1T;@@1a&J;; g* ED 4y1}D$'13xxz ]] CIs4y!TZZ(>$**+EEGF#4 0F "4 0F vw: FF7BL;sH(H6H!c#,K||Ed{y7wrrrr$rrrs r_rec_append_fields_dispatcherrs JOOrc$t||||ddS)aM Add new fields to an existing array. The names of the fields are given with the `names` arguments, the corresponding values with the `data` arguments. If a single field is appended, `names`, `data` and `dtypes` do not have to be lists but just values. Parameters ---------- base : array Input array to extend. names : string, sequence String or sequence of strings corresponding to the names of the new fields. data : array or sequence of arrays Array or sequence of arrays storing the fields to add to the base. dtypes : sequence of datatypes, optional Datatype or sequence of datatypes. If None, the datatypes are estimated from the `data`. See Also -------- append_fields Returns ------- appended_array : np.recarray TF)rrrrorn)rrs rrrs> u4$(% 99r!c|fSrr)rFalignrecurses r_repack_fields_dispatcherrs 4Kr!ct|tjs+t|j||}|j |dS|j |Sg}|j D]R}|j |}|rt|d|d}n|d}t|dk(r|d|f}|j||fTtj||}tj|j|fS) a# Re-pack the fields of a structured array or dtype in memory. The memory layout of structured datatypes allows fields at arbitrary byte offsets. This means the fields can be separated by padding bytes, their offsets can be non-monotonically increasing, and they can overlap. This method removes any overlaps and reorders the fields in memory so they have increasing byte offsets, and adds or removes padding bytes depending on the `align` option, which behaves like the `align` option to `numpy.dtype`. If `align=False`, this method produces a "packed" memory layout in which each field starts at the byte the previous field ended, and any padding bytes are removed. If `align=True`, this methods produces an "aligned" memory layout in which each field's offset is a multiple of its alignment, and the total itemsize is a multiple of the largest alignment, by adding padding bytes as needed. Parameters ---------- a : ndarray or dtype array or dtype for which to repack the fields. align : boolean If true, use an "aligned" memory layout, otherwise use a "packed" layout. recurse : boolean If True, also repack nested structures. Returns ------- repacked : ndarray or dtype Copy of `a` with fields repacked, or `a` itself if no repacking was needed. Examples -------- >>> import numpy as np >>> from numpy.lib import recfunctions as rfn >>> def print_offsets(d): ... print("offsets:", [d.fields[name][1] for name in d.names]) ... print("itemsize:", d.itemsize) ... >>> dt = np.dtype('u1, >> dt dtype({'names': ['f0', 'f1', 'f2'], 'formats': ['u1', '>> print_offsets(dt) offsets: [0, 8, 16] itemsize: 24 >>> packed_dt = rfn.repack_fields(dt) >>> packed_dt dtype([('f0', 'u1'), ('f1', '>> print_offsets(packed_dt) offsets: [0, 1, 9] itemsize: 17 )rrF)rrTr1r) rSrCr#rastyper$r-r&r5r|)rFrrdt fieldinfor/rdfmts rrrsz a " 177% Axxx''wwI &hhtn AeTBCa&C s8q=FD>D$% & )5 )B 88QVVRL !!r!cd}g}|jD]}|j|}|d|d}}||\}}|j.|jtj||ff|||zfat |||z} |j } t|D]I} | dk(r|j| |j| D cgc]\} } }| | || | zzfc}} } K|Scc}} } w)z Returns a flat list of (dtype, count, offset) tuples of all the scalar fields in the dtype "dt", including nested fields, in left to right order. cd}|jdk7r2|jD]}||z} |j}|jdk7r2||fS)NrBr)rr)rrr~s r count_elemz+_get_fields_and_offsets..count_elem^sPhh"n   Bhh"n5yr!rrB) r$r-r5rCr#_get_fields_and_offsetsitemsizeranger;)roffsetrr-r/r(f_dtf_offsetr subfieldsr~ircos rrrUsFS $q58hT"a ::  MM288TA4L11h6GH I/h6GHI==D1X S6MM),MMy"Q"QGAq!Aq!a$h,#7"QR  SS" M#RsC)c(t|dkr|S|d|dk}|rtt|t|}n t||}d}d}|D];\}}|dk7r|ry||}||k7ry||dz |zz} n|} |||z } || }|| k7ry| }=|r| S|S)z Returns the stride between the fields, or None if the stride is not constant. The values in "counts" designate the lengths of subarrays. Subarrays are treated as many contiguous fields, with always positive stride. rBrN)r&rreversed) offsetscountsrnegativeit prev_offsetstriderr end_offset new_strides r_common_striderzs 7|qqzGAJ&H '"HV$4 5 & !K F!  A:~!!519"88JJ  "+-J~## '!*w Mr!c|fSrr)arrr#rcastings r&_structured_to_unstructured_dispatcherr 6Mr!c|jj tdt|j}t |}|dk(r | td|dk(r t dt |\}}}t|D cgc]} d|  } } |+tj|D cgc]} | jc} ntj|tj| |||jjd} |j| }t|tjtjtj fv} |s:| r7t#fd|Dr"t%||j}||j&}|j(t+|jfz}|j,t/|d fz}|d tj0fjtj2}|d t5|df}tj6j8j;|||d }|jd }|dkr |d dddf}t|t|j<ur||}|Stj| |D cgc]} | j(fc} d}|j?|||}|jt+|ffScc} wcc} wcc} w)a{ Converts an n-D structured array into an (n+1)-D unstructured array. The new array will have a new last dimension equal in size to the number of field-elements of the input array. If not supplied, the output datatype is determined from the numpy type promotion rules applied to all the field datatypes. Nested fields, as well as each element of any subarray fields, all count as a single field-elements. Parameters ---------- arr : ndarray Structured array or dtype to convert. Cannot contain object datatype. dtype : dtype, optional The dtype of the output unstructured array. copy : bool, optional If true, always return a copy. If false, a view is returned if possible, such as when the `dtype` and strides of the fields are suitable and the array subtype is one of `numpy.ndarray`, `numpy.recarray` or `numpy.memmap`. .. versionchanged:: 1.25.0 A view can now be returned if the fields are separated by a uniform stride. casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional See casting argument of `numpy.ndarray.astype`. Controls what kind of data casting may occur. Returns ------- unstructured : ndarray Unstructured array with one more dimension. Examples -------- >>> import numpy as np >>> from numpy.lib import recfunctions as rfn >>> a = np.zeros(4, dtype=[('a', 'i4'), ('b', 'f4,u2'), ('c', 'f4', 2)]) >>> a array([(0, (0., 0), [0., 0.]), (0, (0., 0), [0., 0.]), (0, (0., 0), [0., 0.]), (0, (0., 0), [0., 0.])], dtype=[('a', '>> rfn.structured_to_unstructured(a) array([[0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.]]) >>> b = np.array([(1, 2, 5), (4, 5, 7), (7, 8 ,11), (10, 11, 12)], ... dtype=[('x', 'i4'), ('y', 'f4'), ('z', 'f8')]) >>> np.mean(rfn.structured_to_unstructured(b[['x', 'z']]), axis=-1) array([ 3. , 5.5, 9. , 11. ]) Narr must be a structured arrayrz(arr has no fields. Unable to guess dtypez#arr with no fields is not supportedr2r$formatsrrc3<K|]}|jk(ywr)r)r.r out_dtypes rr0z-structured_to_unstructured..s&Jrww)';&JsrB.T)r.rr$rrr) r#r$r%rr&NotImplementedErrorrrrC result_typerrrir|rrmmemmapallr__array_wrap__rsumstridesabsnewaxisuint8minlib stride_tricks as_strided__self__r)rr#rrr-n_fieldsdtsrrrr$rflattened_fieldscan_view common_stridewrap new_shape new_strides packed_fieldsrs @rrrsx yy9:: $SYY /F6{H1}CDD Q!"GHH<C#Ho .qW .E . }NNs$;RWW$;< HHUO xx%,/,3-0YY-?-?!AB ((# $C CyRZZbii@@H h3&Jc&J#J'w 8J8JK  $%%D S[)2D2D$EEI++]);Q(??Kc2::o&++BHH5Cc3w<=()C&&&&11#2;2=8<2>C ((9%f-Cq #tt)nCyT]] 333iJHHuJM)NB9bhh*?)NPQM **]w* ?C 88YV/ 00q /% K'!K,K1 c|fSrr)rr#r$rrrs r&_unstructured_to_structured_dispatcherr.rr!c|jdk(r td|jd}|dk(r td|f|t|Dcgc]}d| }}t j |Dcgc]}||j fc}|}t |} t| \} } } n| tdt j |}t |} t| dk(rggg} } } n t| \} } } |t| k7r td |}|r|js td tt| Dcgc]}d| }}t j || D cgc]} |j | jfc} d }t j|j|}t j || | |jd }|j||| }|j|dScc}wcc}wcc}wcc} w)a* Converts an n-D unstructured array into an (n-1)-D structured array. The last dimension of the input array is converted into a structure, with number of field-elements equal to the size of the last dimension of the input array. By default all output fields have the input array's dtype, but an output structured dtype with an equal number of fields-elements can be supplied instead. Nested fields, as well as each element of any subarray fields, all count towards the number of field-elements. Parameters ---------- arr : ndarray Unstructured array or dtype to convert. dtype : dtype, optional The structured dtype of the output array names : list of strings, optional If dtype is not supplied, this specifies the field names for the output dtype, in order. The field dtypes will be the same as the input array. align : boolean, optional Whether to create an aligned memory layout. copy : bool, optional See copy argument to `numpy.ndarray.astype`. If true, always return a copy. If false, and `dtype` requirements are satisfied, a view is returned. casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional See casting argument of `numpy.ndarray.astype`. Controls what kind of data casting may occur. Returns ------- structured : ndarray Structured array with fewer dimensions. Examples -------- >>> import numpy as np >>> from numpy.lib import recfunctions as rfn >>> dt = np.dtype([('a', 'i4'), ('b', 'f4,u2'), ('c', 'f4', 2)]) >>> a = np.arange(20).reshape((4,5)) >>> a array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]]) >>> rfn.unstructured_to_structured(a, dt) array([( 0, ( 1., 2), [ 3., 4.]), ( 5, ( 6., 7), [ 8., 9.]), (10, (11., 12), [13., 14.]), (15, (16., 17), [18., 19.])], dtype=[('a', 'H c|fSrr)funcrs r_apply_along_fields_dispatcherrs 6Mr!cn|jj tdt|}||dS)al Apply function 'func' as a reduction across fields of a structured array. This is similar to `numpy.apply_along_axis`, but treats the fields of a structured array as an extra axis. The fields are all first cast to a common type following the type-promotion rules from `numpy.result_type` applied to the field's dtypes. Parameters ---------- func : function Function to apply on the "field" dimension. This function must support an `axis` argument, like `numpy.mean`, `numpy.sum`, etc. arr : ndarray Structured array for which to apply func. Returns ------- out : ndarray Result of the reduction operation Examples -------- >>> import numpy as np >>> from numpy.lib import recfunctions as rfn >>> b = np.array([(1, 2, 5), (4, 5, 7), (7, 8 ,11), (10, 11, 12)], ... dtype=[('x', 'i4'), ('y', 'f4'), ('z', 'f8')]) >>> rfn.apply_along_fields(np.mean, b) array([ 2.66666667, 5.33333333, 8.66666667, 11. ]) >>> rfn.apply_along_fields(np.mean, b[['x', 'z']]) array([ 3. , 5.5, 9. , 11. ]) rr)axis)r#r$r%r)rruarrs rrrs6H yy9:: %c *D 2 r!c ||fSrr)dstsrczero_unassigneds r!_assign_fields_by_name_dispatcherrs 8Or!c|jj||d<y|jjD]6}||jjvr |sd||<$t|||||8y)a Assigns values from one structured array to another by field name. Normally in numpy >= 1.14, assignment of one structured array to another copies fields "by position", meaning that the first field from the src is copied to the first field of the dst, and so on, regardless of field name. This function instead copies "by field name", such that fields in the dst are assigned from the identically named field in the src. This applies recursively for nested structures. This is how structure assignment worked in numpy >= 1.6 to <= 1.13. Parameters ---------- dst : ndarray src : ndarray The source and destination arrays during assignment. zero_unassigned : bool, optional If True, fields in the dst for which there was no matching field in the src are filled with the value 0 (zero). This was the behavior of numpy <= 1.13. If False, those fields are not modified. N.r)r#r$r)rrrr/s rrrsh4 yyC 3 syy &D !#d)SY"1 3 3r!c|fSrr)rrequired_dtypes r_require_fields_dispatcherr!s 8Or!c`tj|j|}t|||S)a Casts a structured array to a new dtype using assignment by field-name. This function assigns from the old to the new array by name, so the value of a field in the output array is the value of the field with the same name in the source array. This has the effect of creating a new ndarray containing only the fields "required" by the required_dtype. If a field name in the required_dtype does not exist in the input array, that field is created and set to 0 in the output array. Parameters ---------- a : ndarray array to cast required_dtype : dtype datatype for output array Returns ------- out : ndarray array with the new dtype, with field values copied from the fields in the input array with the same name Examples -------- >>> import numpy as np >>> from numpy.lib import recfunctions as rfn >>> a = np.ones(4, dtype=[('a', 'i4'), ('b', 'f8'), ('c', 'u1')]) >>> rfn.require_fields(a, [('b', 'f4'), ('c', 'u1')]) array([(1., 1), (1., 1), (1., 1), (1., 1)], dtype=[('b', '>> rfn.require_fields(a, [('b', 'f4'), ('newf', 'u1')]) array([(1., 0), (1., 0), (1., 0), (1., 0)], dtype=[('b', '>> import numpy as np >>> from numpy.lib import recfunctions as rfn >>> x = np.array([1, 2,]) >>> rfn.stack_arrays(x) is x True >>> z = np.array([('A', 1), ('B', 2)], dtype=[('A', '|S3'), ('B', float)]) >>> zz = np.array([('a', 10., 100.), ('b', 20., 200.), ('c', 30., 300.)], ... dtype=[('A', '|S3'), ('B', np.double), ('C', np.double)]) >>> test = rfn.stack_arrays((z,zz)) >>> test masked_array(data=[(b'A', 1.0, --), (b'B', 2.0, --), (b'a', 10.0, 100.0), (b'b', 20.0, 200.0), (b'c', 30.0, 300.0)], mask=[(False, False, True), (False, False, True), (False, False, False), (False, False, False), (False, False, False)], fill_value=(b'N/A', 1e+20, 1e+20), dtype=[('A', 'S3'), ('B', ' ''rr2r)rSrCrr&rrr#r$r3r5indexr TypeErrorrg concatenaterrcumsumr_rrprx)r%rurnror&rFrDnrecordsr=rfldnamesdtype_lnewdescrrr$dtype_nfnamefdtypenameidxr@cdtyperrseenrjr/s rrr+sT&"**% V ay39:aq!''):I: )*1A*H*( )!agg )F )!'(A(H(QiGg&H# $41aQ $E $!": S+G4 SME6E!0 U#++e,$W- 6).FF0C(DHW%v%#&9&xq$QRR S S 8} *x 02H=255H-. 8VCR[&*M *LQ1aGGMME}/03t9+'!,*D()$F4L1%4' D)*  * }VX6&: ??M;* )( %s*I$I <I%I*? I/c|fSrr)rFkey ignoremask return_indexs r_find_duplicates_dispatcherr>s 4Kr!ctj|j}t|j}|}|r||D]}||} ||}|j }||}|j } | dd| ddk(} |r|j} d| | dd<tjdg| f} | dd| ddz| dd||| } |r| || fS| S)a Find the duplicates in a structured array along a given key Parameters ---------- a : array-like Input array key : {string, None}, optional Name of the fields along which to check the duplicates. If None, the search is performed by records ignoremask : {True, False}, optional Whether masked data should be discarded or considered as duplicates. return_index : {False, True}, optional Whether to return the indices of the duplicated values. Examples -------- >>> import numpy as np >>> from numpy.lib import recfunctions as rfn >>> ndtype = [('a', int)] >>> a = np.ma.array([1, 1, 1, 2, 2, 3, 3], ... mask=[0, 0, 1, 0, 0, 0, 1]).view(ndtype) >>> rfn.find_duplicates(a, ignoremask=True, return_index=True) (masked_array(data=[(1,), (1,), (2,), (2,)], mask=[(False,), (False,), (False,), (False,)], fill_value=(999999,), dtype=[('a', '>E7D/ *DSb DH$D"I7D!JGDM**r!c  ||fSrr) r;r1r2jointype r1postfix r2postfixrurnros r_join_by_dispatcherrN  8Or!c h |dvrtd|zttrftt tk7r+t fdt D} td| D]N} | |jjvrtd| | |jjvsBtd| |j}|j}t|t|} } |jj|jj}} t | t |zt z }|r|s|sd}|dz }t|| Dcgc] }|vs| }}t||}t||}tj||f}|j }||}tjd g|d d |d d k(f}|d d |d d z|d d ||}||| k}||| k\| z }t|t|}}|dk(rd\}}n|dk(r`||}tj|||| kf}tj|||| k\| z f}t||z t||z }}n8|dk(r3||}tj|||| kf}t||z d}}||||}!} t|j}"t|jD]\}#}$|#vs |"j!|#|$ft|jD]]\}#}$|"D %cgc]\} }%|  }&} }% |&j#|#}'|"|'\}(})|#vr|#t%|$|)f|"|'<J|#|z|)f|#|z|$fg|"|'|'d z_tj|"}"t%||}*tj&|*zzf|"}+|+jj}&| D]7},| |,}-|,|&vs |,|vr |s |,vr|,|z },|+|,}.|-d ||.d ||dvs-|-|d |.|*|*|z9|D]9},|!|,}-|,|&vs |,| vr |s |,vr|,|z },|+|,}.|-d ||.d ||dk(s.|s1|-|d |.| d ;|+j) ||d}/t+t-|+|fi|/Scc}wcc}%} w#t$r|"j!|#|$fYwxYw)a< Join arrays `r1` and `r2` on key `key`. The key should be either a string or a sequence of string corresponding to the fields used to join the array. An exception is raised if the `key` field cannot be found in the two input arrays. Neither `r1` nor `r2` should have any duplicates along `key`: the presence of duplicates will make the output quite unreliable. Note that duplicates are not looked for by the algorithm. Parameters ---------- key : {string, sequence} A string or a sequence of strings corresponding to the fields used for comparison. r1, r2 : arrays Structured arrays. jointype : {'inner', 'outer', 'leftouter'}, optional If 'inner', returns the elements common to both r1 and r2. If 'outer', returns the common elements as well as the elements of r1 not in r2 and the elements of not in r2. If 'leftouter', returns the common elements and the elements of r1 not in r2. r1postfix : string, optional String appended to the names of the fields of r1 that are present in r2 but absent of the key. r2postfix : string, optional String appended to the names of the fields of r2 that are present in r1 but absent of the key. defaults : {dictionary}, optional Dictionary mapping field names to the corresponding default values. usemask : {True, False}, optional Whether to return a MaskedArray (or MaskedRecords is `asrecarray==True`) or a ndarray. asrecarray : {False, True}, optional Whether to return a recarray (or MaskedRecords if `usemask==True`) or just a flexible-type ndarray. Notes ----- * The output is sorted along the key. * A temporary array is formed by dropping the fields not in the key for the two arrays and concatenating the result. This array is then sorted, and the common entries selected. The output is constructed by filling the fields with the selected entries. Matching is not preserved if there are some duplicates... )innerouter leftouterzWThe 'jointype' argument should be in 'inner', 'outer' or 'leftouter' (got '%s' instead)c3>K|]\}}||dzdvs|yw)rBNr)r.rxr;s rr0zjoin_by..s&DA1AEF 3C1Dszduplicate join key zr1 does not have key field zr2 does not have key field z8r1 and r2 contain common names, r1postfix and r2postfix zcan't both be empty)orderFrBNrrQ)rrrRrSrr)rRrSr)r%rSr\r&rnext enumerater#r$rrrgr,r@rCr3r5r*rrsortrprx)0r;rIrJrKrLrMrurnrodupr/nb1nb2r1namesr2names collisionsrrkey1r1kr2kauxidx_sortflag_inidx_inidx_1idx_2r1cmnr2cmnr1spcr2spcidx_outs1s2r=r4r5r#r$r6r@r7cmnrr2selectedr)kwargss0` rrrsth66<>FG  #sf 3s8}C D3DD.sg677E rxx~~ %:4(CD D rxx~~ %:4(CD D E B Bb'3r7#S((.."((..gWg,W-S9J9 H $$o +!!s(A +D + r4 C r4 C ..#s $C{{{%H h-Cnnugs12w#cr(':;a7l9# NA)"6E*  U'/GUFG 0 KKcK ;F }VX6 A& AAs ,V1 + MM5&/ * +s$& R0R5 R RR10R1c ||fSrr)r;rIrJrKrLrMrus r_rec_join_dispatcherrt{rOr!c0||||ddd}t|||fi|S)z Join arrays `r1` and `r2` on keys. Alternative to join_by, that always returns a np.recarray. See Also -------- join_by : equivalent function FT)rKrLrMrurnro)r)r;rIrJrKrLrMrurrs rrrs.#&5NF 3B )& ))r!)F)NN)NT)TFr)NNNN)rFFF)NrTF)FF)r)NNN)NFunsafe)NNNNN)NNFFrv)T)NTFF)NTF)NNNNNN)rQ12NTF)rQrwrxN)?__doc__r`numpyrCnumpy.margnumpy.ma.mrecordsmrecordsrjnumpy._core.overridesrnumpy.lib._iotoolsr__all__r rr3r r r rGrJr rUr]rerprxrzrrrrrrrrrrrrrrrrrrrrrrrrr!rr'rr>r rNrrtrrr!rrs 9. :;$<$N @BB6  8-`   "0" BF6: 1238+0E3EP01:G2:GzG245I6I23%4%P9=HL 23,0:?CG4CGL 67989D23Q"4Q"f#J*ZBF37?@1A1DCGJN?@BG3;i'Ai'V78'9'V:;#3<#3J34)5)X=A:> 12AF"T?3T?p48 45767v?C04 ,-DG49nB.nBd?C -.EH */ *r!