U Dx`@sdZddlZddlZddlmZddlmZmZddlmZddl m Z ddl m Z ddl mZddlmZejjjZd d d d d ddddddddddddddddgZddZe ed dZd!d"Zd#dZd$dZd%dZdpd'd(Zdqd)d*Zdrd+dZd,d-Zd.d/Zdsd1d2Zdtd3d4Z dud5d6Z!dvd7d8Z"e e"dwd:dZ#dxd;d<Z$e e$dyd=d Z%dzd>d?Z&d@dAZ'e e'dBdZ(dCdDZ)e e)dEdZ*d{dFdGZ+e e+d|dHd Z,d}dIdJZ-e e-d~dKdZ.ddLdMZ/e e/ddNdZ0ddOdPZ1ddQdRZ2e e2ddTdZ3ddUdVZ4e e4ddWdZ5dXdYZ6e e6dZd Z7dd[d\Z8e e8dd]d Z9d^d_Z:e e:d`dZ;ddadbZe e>ddfd Z?ddgdhZ@e e@ddldZAddmdnZBe eBddodZCdS)z 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)ndarrayrecarray) MaskedArray) MaskedRecords)array_function_dispatch)_is_string_like)suppress_warnings 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_structuredcCs||fSN)inputoutputrr=/tmp/pip-target-zr53vnty/lib/python/numpy/lib/recfunctions.py!_recursive_fill_fields_dispatcher sr#c Csl|j}|jD]Z}z ||}Wntk r4Yq YnX|jjdk rRt|||q |||dt|<q |S)aj 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 -------- >>> 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', '>> dt = np.dtype([(('a', 'A'), np.int64), ('b', np.double, 3)]) >>> dt.descr [(('a', 'A'), '>> _get_fieldspec(dt) [(('a', 'A'), dtype('int64')), ('b', dtype(('bsz!_get_fieldspec..cSs4g|],\}}t|dkr|n |d|f|dfqS)rr')r-r.frrr" dsz"_get_fieldspec..r%)r$r,rr/r"_get_fieldspecKs   r6cCsPg}|j}|D]8}||}|jdk r<||tt|fq||qt|S)a Returns the field names of the input datatype as a tuple. Parameters ---------- adtype : dtype Input datatype Examples -------- >>> from numpy.lib import recfunctions as rfn >>> rfn.get_names(np.empty((1,), dtype=int)) Traceback (most recent call last): ... AttributeError: 'numpy.ndarray' object has no attribute 'names' >>> rfn.get_names(np.empty((1,), dtype=[('A',int), ('B', float)])) Traceback (most recent call last): ... AttributeError: 'numpy.ndarray' object has no attribute 'names' >>> adtype = np.dtype([('a', int), ('b', [('ba', int), ('bb', int)])]) >>> rfn.get_names(adtype) ('a', ('b', ('ba', 'bb'))) N)r%appendtupleradtypeZ listnamesr%r.r*rrr"rjs  cCsFg}|j}|D].}||||}|jdk r|t|qt|S)a  Returns the field names of the input datatype as a tuple. Nested structure are flattened beforehand. Parameters ---------- adtype : dtype Input datatype Examples -------- >>> from numpy.lib import recfunctions as rfn >>> rfn.get_names_flat(np.empty((1,), dtype=int)) is None Traceback (most recent call last): ... AttributeError: 'numpy.ndarray' object has no attribute 'names' >>> rfn.get_names_flat(np.empty((1,), dtype=[('A',int), ('B', float)])) Traceback (most recent call last): ... AttributeError: 'numpy.ndarray' object has no attribute 'names' >>> adtype = np.dtype([('a', int), ('b', [('ba', int), ('bb', int)])]) >>> rfn.get_names_flat(adtype) ('a', 'b', 'ba', 'bb') N)r%r7extendrr8r9rrr"rs  cCsh|j}|dkrd|ffSg}|D]:}|j|\}}|jdk rL|t|q |||fq t|SdS)aD Flatten a structured data-type description. Examples -------- >>> from numpy.lib import recfunctions as rfn >>> ndtype = np.dtype([('a', '>> rfn.flatten_descr(ndtype) (('a', dtype('int32')), ('ba', dtype('float64')), ('bb', dtype('int32'))) Nr+)r%r,r;rr7r8)ndtyper%descrr)typ_rrr"rs   FcCstg}|r$|D]}|t|jq nF|D]@}|j}|jdk rZt|jdkrZ|t|q(|d|fq(t|S)Nr+)r;rr$r%r'r6r7np) seqarraysflattenr(ar*rrr" _zip_dtypesrEcCst||djS)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. rC)rEr=)rBrCrrr" _zip_descrs rGcCs|dkr i}|j}|D]}||}|jdk rX|r<|g||<ng||<|t|||qdd||gplgD}|r||n |r|g}|pg||<q|S)ab 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 interbally during recursion). Examples -------- >>> 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']} NcSsg|]}|qSrr)r-r?rrr"r4sz&get_fieldstructure..)r%updatergetr7)r:lastnameparentsr%r.r*Z lastparentrrr"rs"   ccs4|D]*}t|tjr(tt|EdHq|VqdS)zu Returns an iterator of concatenated fields from a sequence of arrays, collapsing any nested structure. N) isinstancerAvoid_izip_fields_flatr8iterableelementrrr"rNs rNccsd|D]Z}t|dr,t|ts,t|EdHqt|tjrXtt|dkrXt|EdHq|VqdS)zP Returns an iterator of concatenated fields from a sequence of arrays. __iter__Nr@)hasattrrLstr _izip_fieldsrArMr'r8rOrrr"rU%s rUTccs6|r t}nt}tj|d|iD]}t||VqdS)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)rNrU itertools zip_longestr8)rB fill_valuerCZzipfunctuprrr" _izip_records5s r[cCs>t|tsd}|r"|r:|t}nt|}|r:|t}|S)z Private function: return a recarray, a ndarray, a MaskedArray or a MaskedRecords depending on the input parameters F)rLrviewrmafilledr)r!usemask asrecarrayrrr" _fix_outputMs    racCsX|jj}|j|j|j}}}|p$iD](\}}||kr*|||<|||||<q*|S)zp Update the fill_value and masked data of `output` from the default given in a dictionary defaults. )r$r%datamaskrYitems)r!defaultsr%rbrcrYkvrrr" _fix_defaults^srhcCs|Srr)rBrYrCr_r`rrr"_merge_arrays_dispatcherlsricCst|dkrt|d}t|ttjfr|j}|jdkrJtd|fg}|r`t|fdd|kr| }|r||rvt }qt }n|rt }nt}|j ||dS|f}ndd |D}td d |D}t|}t||d} g} g} |rt||D]\} } || }| }t|  }|rt|| j}t|ttjfrt|jdkr\|d}d}n"tj|| jdd }tjd |jd}nd}d}| t||g|| t||g|qtt| |d}tjtj|| |dtt| |dd}|r| t }nt||D]\} } || }| }|r~t|| j}t|ttjfrt|jdkrj|d}ntj|| jdd }nd}| t||g|q tjtt| |d| |d}|r| t }|S)aR 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 -------- >>> 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', '.css|] }|jVqdSr)sizer-rDrrr"r0szmerge_arrays..)r$Zndmin)r@r/)r$count)rc)r'rArlrLrrMr$r%rEravelrrrr\r8maxzipZ __array__r]Z getmaskarray_check_fill_valueitemarrayZonesr7rWchainr[Zfromiterlist)rBrYrCr_r`ZseqdtypeZseqtypesizesZ maxlengthr(ZseqdataZseqmaskrDnZ nbmissingrbrcZfvalZfmskr!rrr"rqs1          cCs|fSrr)base drop_namesr_r`rrr"_drop_fields_dispatchersr}csXt|r|g}nt|}fdd|j|}tj|j|d}t||}t|||dS)a Return a new array with fields in `drop_names` dropped. Nested fields are supported. .. versionchanged:: 1.18.0 `drop_fields` returns an array with 0 fields if all fields are dropped, rather than returning ``None`` as it did previously. Parameters ---------- base : array Input array drop_names : string or sequence String or sequence of strings corresponding to the names of the fields to drop. 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. Examples -------- >>> 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_descrr/r_r`)rsetr$rAemptyshaperra)r{r|r_r`r(r!rr~r"r s&   cs:fdd|D}tjj|d}t|}t|||dS)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. csg|]}|j|fqSrr/r-rzr{rr"r4Qsz _keep_fields..r/r)rArrrra)r{Z keep_namesr_r`r(r!rrr" _keep_fields>s rcCs|fSrrr{r|rrr"_rec_drop_fields_dispatcherWsrcCst||dddS)zK Returns a new numpy.recarray with fields in `drop_names` dropped. FTr)r rrrr"r[scCs|fSrr)r{ namemapperrrr"_rename_fields_dispatchercsrcs"fdd|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 -------- >>> 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_fields)r$r\)r{rr(rrr"rgs ccs|V|EdHdSrr)r{r%rbdtypesrYr_r`rrr"_append_fields_dispatchersrc CsPt|ttfr,t|t|krBd}t|nt|trB|g}|g}|dkrndd|D}ddt||D}n`t|ttfs|g}t|t|krt|dkr|t|}n d}t|ddt|||D}t|||d }t|dkrt|d ||d }n|}t j t t|t|t |j t |j d }t||}t||}t|||d S)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 namesNcSsg|]}tj|dddqS)FT)copysubok)rArvrorrr"r4sz!append_fields..cSs"g|]\}}|||jfgqSr)r\r$)r-r.rDrrr"r4sr@z5The dtypes argument must be None, a dtype, or a list.cSs0g|](\}}}tj|dd|d||fgqS)FT)rrr$)rArvr\)r-rDrzdrrr"r4s)r_rYT)rCr_rYr/r)rLr8rxr'r&rTrsrpopr] masked_allrrr6r$rra) r{r%rbrrYr_r`msgr!rrr"r sB        ccs|V|EdHdSrrr{r%rbrrrr"_rec_append_fields_dispatchersrcCst||||dddS)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)rbrr`r_)r rrrr"rs cCs|fSrr)rDalignrecurserrr"_repack_fields_dispatchersrcCst|tjs*t|j||d}|j|ddS|jdkr8|Sg}|jD]T}|j|}|rht|d|dd}n|d}t|dkr|d|f}|||fqBtj||d }t|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 `np.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 -------- >>> 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)rNrTr1r) rLrAr$rastyper%r,r'r7rk)rDrrdtZ fieldinfor.rZfmtrrr"rs :      c sdd}g}|jD]}|j|}|d|d}}||\}}|jdkrj|t||ff|||fqt|||} |jt|D]2dkr|| q|fdd| Dqq|S)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. cSs2d}|jdkr*|jD] }||9}q|j}q||fS)Nr@r)rr{)rrprnrrr" count_elembs    z+_get_fields_and_offsets..count_elemrr@Ncs$g|]\}}}|||fqSrr)r-rcoirnrr"r4{sz+_get_fields_and_offsets..) r%r,r7rAr$_get_fields_and_offsetsitemsizeranger;) roffsetrr,r.r)Zf_dtZf_offsetrzZ subfieldsrrr"rYs     "  rcCs|fSrr)arrr$rcastingrrr"&_structured_to_unstructured_dispatchersrunsafec s|jjdkrtdt|j}t|}|dkr@|dkr@tdn|dkrPtdt|\}}}ddt|D} |dkrtj dd|Dn|t| |||jj d } t } | t d || }W5QRXt| fd d|Dd } |j| ||d }|t|ffS)ao 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 See copy argument to `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 `ndarray.astype`. Controls what kind of data casting may occur. Returns ------- unstructured : ndarray Unstructured array with one more dimension. Examples -------- >>> 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 supportedcSsg|]}d|qSzf{}formatrrrr"r4sz.structured_to_unstructured..cSsg|] }|jqSrrr-rrrr"r4sr%formatsoffsetsrzNumpy has detectedcsg|]}|jfqSr)rr out_dtyperr"r4sr%rrr)r$r%r&rr'NotImplementedErrorrsrrAZ result_typerrfilter FutureWarningr\rsum) rr$rrr,n_fieldsdtscountsrr%flattened_fieldssup packed_fieldsrrr"rs44    cCs|fSrr)rr$r%rrrrrr"&_unstructured_to_structured_dispatchersrcshjdkrtdjd}|dkr,td|dkr|dkrNddt|D}tjfd d|D|d }t|}t|\} } } nn|dk rtd t|}t|dkrggg} } } nt|\} } } |t | krtd |}|r|j std ddtt|D}t|fdd| Dd} t  | t|| | |j d} j| ||d |dS)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 `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 `ndarray.astype`. Controls what kind of data casting may occur. Returns ------- structured : ndarray Structured array with fewer dimensions. Examples -------- >>> 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', '.csg|]}|jfqSrr/rrrr"r4$srz!don't supply both dtype and nameszVThe length of the last dimension of arr must be equal to the number of fields in dtypez'align was True but dtype is not alignedcSsg|]}d|qSrrrrrr"r48scsg|]}j|jfqSr)r$rrrrr"r4>srrr).r)rr&rrrAr$rrsr'rZisalignedstructZascontiguousarrayr\rr)rr$r%rrrZn_elemrr,rrrrrrrr"rsD7     cCs|fSrr)funcrrrr"_apply_along_fields_dispatcherKsrcCs(|jjdkrtdt|}||ddS)a@ Apply function 'func' as a reduction across fields of a structured array. This is similar to `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 np.mean, np.sum, etc. arr : ndarray Structured array for which to apply func. Returns ------- out : ndarray Result of the recution operation Examples -------- >>> 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. ]) Nrrj)Zaxis)r$r%r&r)rruarrrrr"r Ns# cCs||fSrr)dstsrczero_unassignedrrr"!_assign_fields_by_name_dispatcherysrcCsX|jjdkr||d<dS|jjD]2}||jjkr>|rRd||<q t|||||q dS)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.rrr"r |s    cCs|fSrr)rvrequired_dtyperrr"_require_fields_dispatchersrcCstj|j|d}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 -------- >>> 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', '>> 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', 1.e+20, 1.e+20), dtype=[('A', 'S3'), ('B', '.cSsg|] }t|qSrr2rorrr"r4scSsg|] }|jqSrr/rorrr"r4scSsg|] }|jqSrr5)r-rrrr"r4scSsg|] \}}|qSrr)r-rzrrrr"r4 sNzIncompatible type '%s' <> '%s'rjzf%ir)rLrr'r6r7indexrr TypeErrorr] concatenaterrArZcumsumZr_rsr$r%rarh)rrer_r`rrBZnrecordsr<ZfldnamesZdtype_lZnewdescrr%Zdtype_nfnamefdtypenameidxr?cdtyper!rseenrDrzrjr.rrr"rsR)       *   cCs|fSrr)rDkey ignoremask return_indexrrr"_find_duplicates_dispatcher.src Cst|}t|j}|}|r>||D] }||}q(||}|}||}|} | dd| ddk} |r|j} d| | dd<tdg| f} | dd| dd| dd<||| } |r| || fS| SdS)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 -------- >>> 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', '.zduplicate join key %rzr1 does not have key field %rzr2 does not have key field %rz8r1 and r2 contain common names, r1postfix and r2postfix zcan't both be emptycsg|]}|kr|qSrrrrrr"r4szjoin_by..)orderFr@Nrjr)rrrrrcss|]\}}|VqdSrr)r-r.r$rrr"r0sr/)rrr)r&rLrTr'rnext enumerater$r%rqrr]rrrAr6r7rxrrrrsortdictrarh)-rrrrrrrer_r`dupr.Znb1Zr1namesZr2namesZ collisionsrkey1Zr1kZr2kZauxZidx_sortZflag_inZidx_inZidx_1Zidx_2Zr1cmnZr2cmnZr1spcZr2spcZidx_outs1s2r<rrr%rr?rZcmnr!r3selectedr*kwargsrrr"rss4         $                $ $  cCs||fSrr)rrrrrrrerrr"_rec_join_dispatcher'srcCs$t||||ddd}t|||f|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)rrrrer_r`)rr)rrrrrrrerrrr"r-s )F)F)NN)NT)TF)N)NNNN)rjFFF)NN)TF)TF)NNNN)NrjTF)N)N)NN)FF)r)NNN)NFr)NNNNN)NNFFr)N)T)NNNN)NTFF)NNN)NTF)NNNNNN)rrrNTF)NNNN)rrrN)D__doc__rWnumpyrAZnumpy.mar]rrrZnumpy.ma.mrecordsrZnumpy.core.overridesrZnumpy.lib._iotoolsrZ numpy.testingrcorert__all__r#rr6rrrrErGrrNrUr[rarhrirr}r rrrrrrr rrrrrrrrrrr rr rrrrrr rrrrrrrr"s$         &$#   /        @   '  F  "  P &  [  g *  % +  X  :  5