fromnumeric.py 139 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233
  1. """Module containing non-deprecated functions borrowed from Numeric.
  2. """
  3. import functools
  4. import math
  5. import types
  6. import numpy as np
  7. from numpy._utils import set_module
  8. from . import _methods, multiarray as mu, numerictypes as nt, overrides, umath as um
  9. from ._multiarray_umath import _array_converter
  10. from .multiarray import asanyarray, asarray, concatenate
  11. _dt_ = nt.sctype2char
  12. # functions that are methods
  13. __all__ = [
  14. 'all', 'amax', 'amin', 'any', 'argmax',
  15. 'argmin', 'argpartition', 'argsort', 'around', 'choose', 'clip',
  16. 'compress', 'cumprod', 'cumsum', 'cumulative_prod', 'cumulative_sum',
  17. 'diagonal', 'mean', 'max', 'min', 'matrix_transpose',
  18. 'ndim', 'nonzero', 'partition', 'prod', 'ptp', 'put',
  19. 'ravel', 'repeat', 'reshape', 'resize', 'round',
  20. 'searchsorted', 'shape', 'size', 'sort', 'squeeze',
  21. 'std', 'sum', 'swapaxes', 'take', 'trace', 'transpose', 'var',
  22. ]
  23. _gentype = types.GeneratorType
  24. # save away Python sum
  25. _sum_ = sum
  26. array_function_dispatch = functools.partial(
  27. overrides.array_function_dispatch, module='numpy')
  28. # functions that are now methods
  29. def _wrapit(obj, method, *args, **kwds):
  30. conv = _array_converter(obj)
  31. # As this already tried the method, subok is maybe quite reasonable here
  32. # but this follows what was done before. TODO: revisit this.
  33. arr, = conv.as_arrays(subok=False)
  34. result = getattr(arr, method)(*args, **kwds)
  35. return conv.wrap(result, to_scalar=False)
  36. def _wrapfunc(obj, method, *args, **kwds):
  37. bound = getattr(obj, method, None)
  38. if bound is None:
  39. return _wrapit(obj, method, *args, **kwds)
  40. try:
  41. return bound(*args, **kwds)
  42. except TypeError:
  43. # A TypeError occurs if the object does have such a method in its
  44. # class, but its signature is not identical to that of NumPy's. This
  45. # situation has occurred in the case of a downstream library like
  46. # 'pandas'.
  47. #
  48. # Call _wrapit from within the except clause to ensure a potential
  49. # exception has a traceback chain.
  50. return _wrapit(obj, method, *args, **kwds)
  51. def _wrapreduction(obj, ufunc, method, axis, dtype, out, **kwargs):
  52. passkwargs = {k: v for k, v in kwargs.items()
  53. if v is not np._NoValue}
  54. if type(obj) is not mu.ndarray:
  55. try:
  56. reduction = getattr(obj, method)
  57. except AttributeError:
  58. pass
  59. else:
  60. # This branch is needed for reductions like any which don't
  61. # support a dtype.
  62. if dtype is not None:
  63. return reduction(axis=axis, dtype=dtype, out=out, **passkwargs)
  64. else:
  65. return reduction(axis=axis, out=out, **passkwargs)
  66. return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
  67. def _wrapreduction_any_all(obj, ufunc, method, axis, out, **kwargs):
  68. # Same as above function, but dtype is always bool (but never passed on)
  69. passkwargs = {k: v for k, v in kwargs.items()
  70. if v is not np._NoValue}
  71. if type(obj) is not mu.ndarray:
  72. try:
  73. reduction = getattr(obj, method)
  74. except AttributeError:
  75. pass
  76. else:
  77. return reduction(axis=axis, out=out, **passkwargs)
  78. return ufunc.reduce(obj, axis, bool, out, **passkwargs)
  79. def _take_dispatcher(a, indices, axis=None, out=None, mode=None):
  80. return (a, out)
  81. @array_function_dispatch(_take_dispatcher)
  82. def take(a, indices, axis=None, out=None, mode='raise'):
  83. """
  84. Take elements from an array along an axis.
  85. When axis is not None, this function does the same thing as "fancy"
  86. indexing (indexing arrays using arrays); however, it can be easier to use
  87. if you need elements along a given axis. A call such as
  88. ``np.take(arr, indices, axis=3)`` is equivalent to
  89. ``arr[:,:,:,indices,...]``.
  90. Explained without fancy indexing, this is equivalent to the following use
  91. of `ndindex`, which sets each of ``ii``, ``jj``, and ``kk`` to a tuple of
  92. indices::
  93. Ni, Nk = a.shape[:axis], a.shape[axis+1:]
  94. Nj = indices.shape
  95. for ii in ndindex(Ni):
  96. for jj in ndindex(Nj):
  97. for kk in ndindex(Nk):
  98. out[ii + jj + kk] = a[ii + (indices[jj],) + kk]
  99. Parameters
  100. ----------
  101. a : array_like (Ni..., M, Nk...)
  102. The source array.
  103. indices : array_like (Nj...)
  104. The indices of the values to extract.
  105. Also allow scalars for indices.
  106. axis : int, optional
  107. The axis over which to select values. By default, the flattened
  108. input array is used.
  109. out : ndarray, optional (Ni..., Nj..., Nk...)
  110. If provided, the result will be placed in this array. It should
  111. be of the appropriate shape and dtype. Note that `out` is always
  112. buffered if `mode='raise'`; use other modes for better performance.
  113. mode : {'raise', 'wrap', 'clip'}, optional
  114. Specifies how out-of-bounds indices will behave.
  115. * 'raise' -- raise an error (default)
  116. * 'wrap' -- wrap around
  117. * 'clip' -- clip to the range
  118. 'clip' mode means that all indices that are too large are replaced
  119. by the index that addresses the last element along that axis. Note
  120. that this disables indexing with negative numbers.
  121. Returns
  122. -------
  123. out : ndarray (Ni..., Nj..., Nk...)
  124. The returned array has the same type as `a`.
  125. See Also
  126. --------
  127. compress : Take elements using a boolean mask
  128. ndarray.take : equivalent method
  129. take_along_axis : Take elements by matching the array and the index arrays
  130. Notes
  131. -----
  132. By eliminating the inner loop in the description above, and using `s_` to
  133. build simple slice objects, `take` can be expressed in terms of applying
  134. fancy indexing to each 1-d slice::
  135. Ni, Nk = a.shape[:axis], a.shape[axis+1:]
  136. for ii in ndindex(Ni):
  137. for kk in ndindex(Nk):
  138. out[ii + s_[...,] + kk] = a[ii + s_[:,] + kk][indices]
  139. For this reason, it is equivalent to (but faster than) the following use
  140. of `apply_along_axis`::
  141. out = np.apply_along_axis(lambda a_1d: a_1d[indices], axis, a)
  142. Examples
  143. --------
  144. >>> import numpy as np
  145. >>> a = [4, 3, 5, 7, 6, 8]
  146. >>> indices = [0, 1, 4]
  147. >>> np.take(a, indices)
  148. array([4, 3, 6])
  149. In this example if `a` is an ndarray, "fancy" indexing can be used.
  150. >>> a = np.array(a)
  151. >>> a[indices]
  152. array([4, 3, 6])
  153. If `indices` is not one dimensional, the output also has these dimensions.
  154. >>> np.take(a, [[0, 1], [2, 3]])
  155. array([[4, 3],
  156. [5, 7]])
  157. """
  158. return _wrapfunc(a, 'take', indices, axis=axis, out=out, mode=mode)
  159. def _reshape_dispatcher(a, /, shape, order=None, *, copy=None):
  160. return (a,)
  161. @array_function_dispatch(_reshape_dispatcher)
  162. def reshape(a, /, shape, order='C', *, copy=None):
  163. """
  164. Gives a new shape to an array without changing its data.
  165. Parameters
  166. ----------
  167. a : array_like
  168. Array to be reshaped.
  169. shape : int or tuple of ints
  170. The new shape should be compatible with the original shape. If
  171. an integer, then the result will be a 1-D array of that length.
  172. One shape dimension can be -1. In this case, the value is
  173. inferred from the length of the array and remaining dimensions.
  174. order : {'C', 'F', 'A'}, optional
  175. Read the elements of ``a`` using this index order, and place the
  176. elements into the reshaped array using this index order. 'C'
  177. means to read / write the elements using C-like index order,
  178. with the last axis index changing fastest, back to the first
  179. axis index changing slowest. 'F' means to read / write the
  180. elements using Fortran-like index order, with the first index
  181. changing fastest, and the last index changing slowest. Note that
  182. the 'C' and 'F' options take no account of the memory layout of
  183. the underlying array, and only refer to the order of indexing.
  184. 'A' means to read / write the elements in Fortran-like index
  185. order if ``a`` is Fortran *contiguous* in memory, C-like order
  186. otherwise.
  187. copy : bool, optional
  188. If ``True``, then the array data is copied. If ``None``, a copy will
  189. only be made if it's required by ``order``. For ``False`` it raises
  190. a ``ValueError`` if a copy cannot be avoided. Default: ``None``.
  191. Returns
  192. -------
  193. reshaped_array : ndarray
  194. This will be a new view object if possible; otherwise, it will
  195. be a copy. Note there is no guarantee of the *memory layout* (C- or
  196. Fortran- contiguous) of the returned array.
  197. See Also
  198. --------
  199. ndarray.reshape : Equivalent method.
  200. Notes
  201. -----
  202. It is not always possible to change the shape of an array without copying
  203. the data.
  204. The ``order`` keyword gives the index ordering both for *fetching*
  205. the values from ``a``, and then *placing* the values into the output
  206. array. For example, let's say you have an array:
  207. >>> a = np.arange(6).reshape((3, 2))
  208. >>> a
  209. array([[0, 1],
  210. [2, 3],
  211. [4, 5]])
  212. You can think of reshaping as first raveling the array (using the given
  213. index order), then inserting the elements from the raveled array into the
  214. new array using the same kind of index ordering as was used for the
  215. raveling.
  216. >>> np.reshape(a, (2, 3)) # C-like index ordering
  217. array([[0, 1, 2],
  218. [3, 4, 5]])
  219. >>> np.reshape(np.ravel(a), (2, 3)) # equivalent to C ravel then C reshape
  220. array([[0, 1, 2],
  221. [3, 4, 5]])
  222. >>> np.reshape(a, (2, 3), order='F') # Fortran-like index ordering
  223. array([[0, 4, 3],
  224. [2, 1, 5]])
  225. >>> np.reshape(np.ravel(a, order='F'), (2, 3), order='F')
  226. array([[0, 4, 3],
  227. [2, 1, 5]])
  228. Examples
  229. --------
  230. >>> import numpy as np
  231. >>> a = np.array([[1,2,3], [4,5,6]])
  232. >>> np.reshape(a, 6)
  233. array([1, 2, 3, 4, 5, 6])
  234. >>> np.reshape(a, 6, order='F')
  235. array([1, 4, 2, 5, 3, 6])
  236. >>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2
  237. array([[1, 2],
  238. [3, 4],
  239. [5, 6]])
  240. """
  241. if copy is not None:
  242. return _wrapfunc(a, 'reshape', shape, order=order, copy=copy)
  243. return _wrapfunc(a, 'reshape', shape, order=order)
  244. def _choose_dispatcher(a, choices, out=None, mode=None):
  245. yield a
  246. yield from choices
  247. yield out
  248. @array_function_dispatch(_choose_dispatcher)
  249. def choose(a, choices, out=None, mode='raise'):
  250. """
  251. Construct an array from an index array and a list of arrays to choose from.
  252. First of all, if confused or uncertain, definitely look at the Examples -
  253. in its full generality, this function is less simple than it might
  254. seem from the following code description::
  255. np.choose(a,c) == np.array([c[a[I]][I] for I in np.ndindex(a.shape)])
  256. But this omits some subtleties. Here is a fully general summary:
  257. Given an "index" array (`a`) of integers and a sequence of ``n`` arrays
  258. (`choices`), `a` and each choice array are first broadcast, as necessary,
  259. to arrays of a common shape; calling these *Ba* and *Bchoices[i], i =
  260. 0,...,n-1* we have that, necessarily, ``Ba.shape == Bchoices[i].shape``
  261. for each ``i``. Then, a new array with shape ``Ba.shape`` is created as
  262. follows:
  263. * if ``mode='raise'`` (the default), then, first of all, each element of
  264. ``a`` (and thus ``Ba``) must be in the range ``[0, n-1]``; now, suppose
  265. that ``i`` (in that range) is the value at the ``(j0, j1, ..., jm)``
  266. position in ``Ba`` - then the value at the same position in the new array
  267. is the value in ``Bchoices[i]`` at that same position;
  268. * if ``mode='wrap'``, values in `a` (and thus `Ba`) may be any (signed)
  269. integer; modular arithmetic is used to map integers outside the range
  270. `[0, n-1]` back into that range; and then the new array is constructed
  271. as above;
  272. * if ``mode='clip'``, values in `a` (and thus ``Ba``) may be any (signed)
  273. integer; negative integers are mapped to 0; values greater than ``n-1``
  274. are mapped to ``n-1``; and then the new array is constructed as above.
  275. Parameters
  276. ----------
  277. a : int array
  278. This array must contain integers in ``[0, n-1]``, where ``n`` is the
  279. number of choices, unless ``mode=wrap`` or ``mode=clip``, in which
  280. cases any integers are permissible.
  281. choices : sequence of arrays
  282. Choice arrays. `a` and all of the choices must be broadcastable to the
  283. same shape. If `choices` is itself an array (not recommended), then
  284. its outermost dimension (i.e., the one corresponding to
  285. ``choices.shape[0]``) is taken as defining the "sequence".
  286. out : array, optional
  287. If provided, the result will be inserted into this array. It should
  288. be of the appropriate shape and dtype. Note that `out` is always
  289. buffered if ``mode='raise'``; use other modes for better performance.
  290. mode : {'raise' (default), 'wrap', 'clip'}, optional
  291. Specifies how indices outside ``[0, n-1]`` will be treated:
  292. * 'raise' : an exception is raised
  293. * 'wrap' : value becomes value mod ``n``
  294. * 'clip' : values < 0 are mapped to 0, values > n-1 are mapped to n-1
  295. Returns
  296. -------
  297. merged_array : array
  298. The merged result.
  299. Raises
  300. ------
  301. ValueError: shape mismatch
  302. If `a` and each choice array are not all broadcastable to the same
  303. shape.
  304. See Also
  305. --------
  306. ndarray.choose : equivalent method
  307. numpy.take_along_axis : Preferable if `choices` is an array
  308. Notes
  309. -----
  310. To reduce the chance of misinterpretation, even though the following
  311. "abuse" is nominally supported, `choices` should neither be, nor be
  312. thought of as, a single array, i.e., the outermost sequence-like container
  313. should be either a list or a tuple.
  314. Examples
  315. --------
  316. >>> import numpy as np
  317. >>> choices = [[0, 1, 2, 3], [10, 11, 12, 13],
  318. ... [20, 21, 22, 23], [30, 31, 32, 33]]
  319. >>> np.choose([2, 3, 1, 0], choices
  320. ... # the first element of the result will be the first element of the
  321. ... # third (2+1) "array" in choices, namely, 20; the second element
  322. ... # will be the second element of the fourth (3+1) choice array, i.e.,
  323. ... # 31, etc.
  324. ... )
  325. array([20, 31, 12, 3])
  326. >>> np.choose([2, 4, 1, 0], choices, mode='clip') # 4 goes to 3 (4-1)
  327. array([20, 31, 12, 3])
  328. >>> # because there are 4 choice arrays
  329. >>> np.choose([2, 4, 1, 0], choices, mode='wrap') # 4 goes to (4 mod 4)
  330. array([20, 1, 12, 3])
  331. >>> # i.e., 0
  332. A couple examples illustrating how choose broadcasts:
  333. >>> a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
  334. >>> choices = [-10, 10]
  335. >>> np.choose(a, choices)
  336. array([[ 10, -10, 10],
  337. [-10, 10, -10],
  338. [ 10, -10, 10]])
  339. >>> # With thanks to Anne Archibald
  340. >>> a = np.array([0, 1]).reshape((2,1,1))
  341. >>> c1 = np.array([1, 2, 3]).reshape((1,3,1))
  342. >>> c2 = np.array([-1, -2, -3, -4, -5]).reshape((1,1,5))
  343. >>> np.choose(a, (c1, c2)) # result is 2x3x5, res[0,:,:]=c1, res[1,:,:]=c2
  344. array([[[ 1, 1, 1, 1, 1],
  345. [ 2, 2, 2, 2, 2],
  346. [ 3, 3, 3, 3, 3]],
  347. [[-1, -2, -3, -4, -5],
  348. [-1, -2, -3, -4, -5],
  349. [-1, -2, -3, -4, -5]]])
  350. """
  351. return _wrapfunc(a, 'choose', choices, out=out, mode=mode)
  352. def _repeat_dispatcher(a, repeats, axis=None):
  353. return (a,)
  354. @array_function_dispatch(_repeat_dispatcher)
  355. def repeat(a, repeats, axis=None):
  356. """
  357. Repeat each element of an array after themselves
  358. Parameters
  359. ----------
  360. a : array_like
  361. Input array.
  362. repeats : int or array of ints
  363. The number of repetitions for each element. `repeats` is broadcasted
  364. to fit the shape of the given axis.
  365. axis : int, optional
  366. The axis along which to repeat values. By default, use the
  367. flattened input array, and return a flat output array.
  368. Returns
  369. -------
  370. repeated_array : ndarray
  371. Output array which has the same shape as `a`, except along
  372. the given axis.
  373. See Also
  374. --------
  375. tile : Tile an array.
  376. unique : Find the unique elements of an array.
  377. Examples
  378. --------
  379. >>> import numpy as np
  380. >>> np.repeat(3, 4)
  381. array([3, 3, 3, 3])
  382. >>> x = np.array([[1,2],[3,4]])
  383. >>> np.repeat(x, 2)
  384. array([1, 1, 2, 2, 3, 3, 4, 4])
  385. >>> np.repeat(x, 3, axis=1)
  386. array([[1, 1, 1, 2, 2, 2],
  387. [3, 3, 3, 4, 4, 4]])
  388. >>> np.repeat(x, [1, 2], axis=0)
  389. array([[1, 2],
  390. [3, 4],
  391. [3, 4]])
  392. """
  393. return _wrapfunc(a, 'repeat', repeats, axis=axis)
  394. def _put_dispatcher(a, ind, v, mode=None):
  395. return (a, ind, v)
  396. @array_function_dispatch(_put_dispatcher)
  397. def put(a, ind, v, mode='raise'):
  398. """
  399. Replaces specified elements of an array with given values.
  400. The indexing works on the flattened target array. `put` is roughly
  401. equivalent to:
  402. ::
  403. a.flat[ind] = v
  404. Parameters
  405. ----------
  406. a : ndarray
  407. Target array.
  408. ind : array_like
  409. Target indices, interpreted as integers.
  410. v : array_like
  411. Values to place in `a` at target indices. If `v` is shorter than
  412. `ind` it will be repeated as necessary.
  413. mode : {'raise', 'wrap', 'clip'}, optional
  414. Specifies how out-of-bounds indices will behave.
  415. * 'raise' -- raise an error (default)
  416. * 'wrap' -- wrap around
  417. * 'clip' -- clip to the range
  418. 'clip' mode means that all indices that are too large are replaced
  419. by the index that addresses the last element along that axis. Note
  420. that this disables indexing with negative numbers. In 'raise' mode,
  421. if an exception occurs the target array may still be modified.
  422. See Also
  423. --------
  424. putmask, place
  425. put_along_axis : Put elements by matching the array and the index arrays
  426. Examples
  427. --------
  428. >>> import numpy as np
  429. >>> a = np.arange(5)
  430. >>> np.put(a, [0, 2], [-44, -55])
  431. >>> a
  432. array([-44, 1, -55, 3, 4])
  433. >>> a = np.arange(5)
  434. >>> np.put(a, 22, -5, mode='clip')
  435. >>> a
  436. array([ 0, 1, 2, 3, -5])
  437. """
  438. try:
  439. put = a.put
  440. except AttributeError as e:
  441. raise TypeError(f"argument 1 must be numpy.ndarray, not {type(a)}") from e
  442. return put(ind, v, mode=mode)
  443. def _swapaxes_dispatcher(a, axis1, axis2):
  444. return (a,)
  445. @array_function_dispatch(_swapaxes_dispatcher)
  446. def swapaxes(a, axis1, axis2):
  447. """
  448. Interchange two axes of an array.
  449. Parameters
  450. ----------
  451. a : array_like
  452. Input array.
  453. axis1 : int
  454. First axis.
  455. axis2 : int
  456. Second axis.
  457. Returns
  458. -------
  459. a_swapped : ndarray
  460. For NumPy >= 1.10.0, if `a` is an ndarray, then a view of `a` is
  461. returned; otherwise a new array is created. For earlier NumPy
  462. versions a view of `a` is returned only if the order of the
  463. axes is changed, otherwise the input array is returned.
  464. Examples
  465. --------
  466. >>> import numpy as np
  467. >>> x = np.array([[1,2,3]])
  468. >>> np.swapaxes(x,0,1)
  469. array([[1],
  470. [2],
  471. [3]])
  472. >>> x = np.array([[[0,1],[2,3]],[[4,5],[6,7]]])
  473. >>> x
  474. array([[[0, 1],
  475. [2, 3]],
  476. [[4, 5],
  477. [6, 7]]])
  478. >>> np.swapaxes(x,0,2)
  479. array([[[0, 4],
  480. [2, 6]],
  481. [[1, 5],
  482. [3, 7]]])
  483. """
  484. return _wrapfunc(a, 'swapaxes', axis1, axis2)
  485. def _transpose_dispatcher(a, axes=None):
  486. return (a,)
  487. @array_function_dispatch(_transpose_dispatcher)
  488. def transpose(a, axes=None):
  489. """
  490. Returns an array with axes transposed.
  491. For a 1-D array, this returns an unchanged view of the original array, as a
  492. transposed vector is simply the same vector.
  493. To convert a 1-D array into a 2-D column vector, an additional dimension
  494. must be added, e.g., ``np.atleast_2d(a).T`` achieves this, as does
  495. ``a[:, np.newaxis]``.
  496. For a 2-D array, this is the standard matrix transpose.
  497. For an n-D array, if axes are given, their order indicates how the
  498. axes are permuted (see Examples). If axes are not provided, then
  499. ``transpose(a).shape == a.shape[::-1]``.
  500. Parameters
  501. ----------
  502. a : array_like
  503. Input array.
  504. axes : tuple or list of ints, optional
  505. If specified, it must be a tuple or list which contains a permutation
  506. of [0, 1, ..., N-1] where N is the number of axes of `a`. Negative
  507. indices can also be used to specify axes. The i-th axis of the returned
  508. array will correspond to the axis numbered ``axes[i]`` of the input.
  509. If not specified, defaults to ``range(a.ndim)[::-1]``, which reverses
  510. the order of the axes.
  511. Returns
  512. -------
  513. p : ndarray
  514. `a` with its axes permuted. A view is returned whenever possible.
  515. See Also
  516. --------
  517. ndarray.transpose : Equivalent method.
  518. moveaxis : Move axes of an array to new positions.
  519. argsort : Return the indices that would sort an array.
  520. Notes
  521. -----
  522. Use ``transpose(a, argsort(axes))`` to invert the transposition of tensors
  523. when using the `axes` keyword argument.
  524. Examples
  525. --------
  526. >>> import numpy as np
  527. >>> a = np.array([[1, 2], [3, 4]])
  528. >>> a
  529. array([[1, 2],
  530. [3, 4]])
  531. >>> np.transpose(a)
  532. array([[1, 3],
  533. [2, 4]])
  534. >>> a = np.array([1, 2, 3, 4])
  535. >>> a
  536. array([1, 2, 3, 4])
  537. >>> np.transpose(a)
  538. array([1, 2, 3, 4])
  539. >>> a = np.ones((1, 2, 3))
  540. >>> np.transpose(a, (1, 0, 2)).shape
  541. (2, 1, 3)
  542. >>> a = np.ones((2, 3, 4, 5))
  543. >>> np.transpose(a).shape
  544. (5, 4, 3, 2)
  545. >>> a = np.arange(3*4*5).reshape((3, 4, 5))
  546. >>> np.transpose(a, (-1, 0, -2)).shape
  547. (5, 3, 4)
  548. """
  549. return _wrapfunc(a, 'transpose', axes)
  550. def _matrix_transpose_dispatcher(x):
  551. return (x,)
  552. @array_function_dispatch(_matrix_transpose_dispatcher)
  553. def matrix_transpose(x, /):
  554. """
  555. Transposes a matrix (or a stack of matrices) ``x``.
  556. This function is Array API compatible.
  557. Parameters
  558. ----------
  559. x : array_like
  560. Input array having shape (..., M, N) and whose two innermost
  561. dimensions form ``MxN`` matrices.
  562. Returns
  563. -------
  564. out : ndarray
  565. An array containing the transpose for each matrix and having shape
  566. (..., N, M).
  567. See Also
  568. --------
  569. transpose : Generic transpose method.
  570. Examples
  571. --------
  572. >>> import numpy as np
  573. >>> np.matrix_transpose([[1, 2], [3, 4]])
  574. array([[1, 3],
  575. [2, 4]])
  576. >>> np.matrix_transpose([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
  577. array([[[1, 3],
  578. [2, 4]],
  579. [[5, 7],
  580. [6, 8]]])
  581. """
  582. x = asanyarray(x)
  583. if x.ndim < 2:
  584. raise ValueError(
  585. f"Input array must be at least 2-dimensional, but it is {x.ndim}"
  586. )
  587. return swapaxes(x, -1, -2)
  588. def _partition_dispatcher(a, kth, axis=None, kind=None, order=None):
  589. return (a,)
  590. @array_function_dispatch(_partition_dispatcher)
  591. def partition(a, kth, axis=-1, kind='introselect', order=None):
  592. """
  593. Return a partitioned copy of an array.
  594. Creates a copy of the array and partially sorts it in such a way that
  595. the value of the element in k-th position is in the position it would be
  596. in a sorted array. In the output array, all elements smaller than the k-th
  597. element are located to the left of this element and all equal or greater
  598. are located to its right. The ordering of the elements in the two
  599. partitions on the either side of the k-th element in the output array is
  600. undefined.
  601. Parameters
  602. ----------
  603. a : array_like
  604. Array to be sorted.
  605. kth : int or sequence of ints
  606. Element index to partition by. The k-th value of the element
  607. will be in its final sorted position and all smaller elements
  608. will be moved before it and all equal or greater elements behind
  609. it. The order of all elements in the partitions is undefined. If
  610. provided with a sequence of k-th it will partition all elements
  611. indexed by k-th of them into their sorted position at once.
  612. axis : int or None, optional
  613. Axis along which to sort. If None, the array is flattened before
  614. sorting. The default is -1, which sorts along the last axis.
  615. kind : {'introselect'}, optional
  616. Selection algorithm. Default is 'introselect'.
  617. order : str or list of str, optional
  618. When `a` is an array with fields defined, this argument
  619. specifies which fields to compare first, second, etc. A single
  620. field can be specified as a string. Not all fields need be
  621. specified, but unspecified fields will still be used, in the
  622. order in which they come up in the dtype, to break ties.
  623. Returns
  624. -------
  625. partitioned_array : ndarray
  626. Array of the same type and shape as `a`.
  627. See Also
  628. --------
  629. ndarray.partition : Method to sort an array in-place.
  630. argpartition : Indirect partition.
  631. sort : Full sorting
  632. Notes
  633. -----
  634. The various selection algorithms are characterized by their average
  635. speed, worst case performance, work space size, and whether they are
  636. stable. A stable sort keeps items with the same key in the same
  637. relative order. The available algorithms have the following
  638. properties:
  639. ================= ======= ============= ============ =======
  640. kind speed worst case work space stable
  641. ================= ======= ============= ============ =======
  642. 'introselect' 1 O(n) 0 no
  643. ================= ======= ============= ============ =======
  644. All the partition algorithms make temporary copies of the data when
  645. partitioning along any but the last axis. Consequently,
  646. partitioning along the last axis is faster and uses less space than
  647. partitioning along any other axis.
  648. The sort order for complex numbers is lexicographic. If both the
  649. real and imaginary parts are non-nan then the order is determined by
  650. the real parts except when they are equal, in which case the order
  651. is determined by the imaginary parts.
  652. The sort order of ``np.nan`` is bigger than ``np.inf``.
  653. Examples
  654. --------
  655. >>> import numpy as np
  656. >>> a = np.array([7, 1, 7, 7, 1, 5, 7, 2, 3, 2, 6, 2, 3, 0])
  657. >>> p = np.partition(a, 4)
  658. >>> p
  659. array([0, 1, 2, 1, 2, 5, 2, 3, 3, 6, 7, 7, 7, 7]) # may vary
  660. ``p[4]`` is 2; all elements in ``p[:4]`` are less than or equal
  661. to ``p[4]``, and all elements in ``p[5:]`` are greater than or
  662. equal to ``p[4]``. The partition is::
  663. [0, 1, 2, 1], [2], [5, 2, 3, 3, 6, 7, 7, 7, 7]
  664. The next example shows the use of multiple values passed to `kth`.
  665. >>> p2 = np.partition(a, (4, 8))
  666. >>> p2
  667. array([0, 1, 2, 1, 2, 3, 3, 2, 5, 6, 7, 7, 7, 7])
  668. ``p2[4]`` is 2 and ``p2[8]`` is 5. All elements in ``p2[:4]``
  669. are less than or equal to ``p2[4]``, all elements in ``p2[5:8]``
  670. are greater than or equal to ``p2[4]`` and less than or equal to
  671. ``p2[8]``, and all elements in ``p2[9:]`` are greater than or
  672. equal to ``p2[8]``. The partition is::
  673. [0, 1, 2, 1], [2], [3, 3, 2], [5], [6, 7, 7, 7, 7]
  674. """
  675. if axis is None:
  676. # flatten returns (1, N) for np.matrix, so always use the last axis
  677. a = asanyarray(a).flatten()
  678. axis = -1
  679. else:
  680. a = asanyarray(a).copy(order="K")
  681. a.partition(kth, axis=axis, kind=kind, order=order)
  682. return a
  683. def _argpartition_dispatcher(a, kth, axis=None, kind=None, order=None):
  684. return (a,)
  685. @array_function_dispatch(_argpartition_dispatcher)
  686. def argpartition(a, kth, axis=-1, kind='introselect', order=None):
  687. """
  688. Perform an indirect partition along the given axis using the
  689. algorithm specified by the `kind` keyword. It returns an array of
  690. indices of the same shape as `a` that index data along the given
  691. axis in partitioned order.
  692. Parameters
  693. ----------
  694. a : array_like
  695. Array to sort.
  696. kth : int or sequence of ints
  697. Element index to partition by. The k-th element will be in its
  698. final sorted position and all smaller elements will be moved
  699. before it and all larger elements behind it. The order of all
  700. elements in the partitions is undefined. If provided with a
  701. sequence of k-th it will partition all of them into their sorted
  702. position at once.
  703. axis : int or None, optional
  704. Axis along which to sort. The default is -1 (the last axis). If
  705. None, the flattened array is used.
  706. kind : {'introselect'}, optional
  707. Selection algorithm. Default is 'introselect'
  708. order : str or list of str, optional
  709. When `a` is an array with fields defined, this argument
  710. specifies which fields to compare first, second, etc. A single
  711. field can be specified as a string, and not all fields need be
  712. specified, but unspecified fields will still be used, in the
  713. order in which they come up in the dtype, to break ties.
  714. Returns
  715. -------
  716. index_array : ndarray, int
  717. Array of indices that partition `a` along the specified axis.
  718. If `a` is one-dimensional, ``a[index_array]`` yields a partitioned `a`.
  719. More generally, ``np.take_along_axis(a, index_array, axis=axis)``
  720. always yields the partitioned `a`, irrespective of dimensionality.
  721. See Also
  722. --------
  723. partition : Describes partition algorithms used.
  724. ndarray.partition : Inplace partition.
  725. argsort : Full indirect sort.
  726. take_along_axis : Apply ``index_array`` from argpartition
  727. to an array as if by calling partition.
  728. Notes
  729. -----
  730. The returned indices are not guaranteed to be sorted according to
  731. the values. Furthermore, the default selection algorithm ``introselect``
  732. is unstable, and hence the returned indices are not guaranteed
  733. to be the earliest/latest occurrence of the element.
  734. `argpartition` works for real/complex inputs with nan values,
  735. see `partition` for notes on the enhanced sort order and
  736. different selection algorithms.
  737. Examples
  738. --------
  739. One dimensional array:
  740. >>> import numpy as np
  741. >>> x = np.array([3, 4, 2, 1])
  742. >>> x[np.argpartition(x, 3)]
  743. array([2, 1, 3, 4]) # may vary
  744. >>> x[np.argpartition(x, (1, 3))]
  745. array([1, 2, 3, 4]) # may vary
  746. >>> x = [3, 4, 2, 1]
  747. >>> np.array(x)[np.argpartition(x, 3)]
  748. array([2, 1, 3, 4]) # may vary
  749. Multi-dimensional array:
  750. >>> x = np.array([[3, 4, 2], [1, 3, 1]])
  751. >>> index_array = np.argpartition(x, kth=1, axis=-1)
  752. >>> # below is the same as np.partition(x, kth=1)
  753. >>> np.take_along_axis(x, index_array, axis=-1)
  754. array([[2, 3, 4],
  755. [1, 1, 3]])
  756. """
  757. return _wrapfunc(a, 'argpartition', kth, axis=axis, kind=kind, order=order)
  758. def _sort_dispatcher(a, axis=None, kind=None, order=None, *, stable=None):
  759. return (a,)
  760. @array_function_dispatch(_sort_dispatcher)
  761. def sort(a, axis=-1, kind=None, order=None, *, stable=None):
  762. """
  763. Return a sorted copy of an array.
  764. Parameters
  765. ----------
  766. a : array_like
  767. Array to be sorted.
  768. axis : int or None, optional
  769. Axis along which to sort. If None, the array is flattened before
  770. sorting. The default is -1, which sorts along the last axis.
  771. kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
  772. Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
  773. and 'mergesort' use timsort or radix sort under the covers and,
  774. in general, the actual implementation will vary with data type.
  775. The 'mergesort' option is retained for backwards compatibility.
  776. order : str or list of str, optional
  777. When `a` is an array with fields defined, this argument specifies
  778. which fields to compare first, second, etc. A single field can
  779. be specified as a string, and not all fields need be specified,
  780. but unspecified fields will still be used, in the order in which
  781. they come up in the dtype, to break ties.
  782. stable : bool, optional
  783. Sort stability. If ``True``, the returned array will maintain
  784. the relative order of ``a`` values which compare as equal.
  785. If ``False`` or ``None``, this is not guaranteed. Internally,
  786. this option selects ``kind='stable'``. Default: ``None``.
  787. .. versionadded:: 2.0.0
  788. Returns
  789. -------
  790. sorted_array : ndarray
  791. Array of the same type and shape as `a`.
  792. See Also
  793. --------
  794. ndarray.sort : Method to sort an array in-place.
  795. argsort : Indirect sort.
  796. lexsort : Indirect stable sort on multiple keys.
  797. searchsorted : Find elements in a sorted array.
  798. partition : Partial sort.
  799. Notes
  800. -----
  801. The various sorting algorithms are characterized by their average speed,
  802. worst case performance, work space size, and whether they are stable. A
  803. stable sort keeps items with the same key in the same relative
  804. order. The four algorithms implemented in NumPy have the following
  805. properties:
  806. =========== ======= ============= ============ ========
  807. kind speed worst case work space stable
  808. =========== ======= ============= ============ ========
  809. 'quicksort' 1 O(n^2) 0 no
  810. 'heapsort' 3 O(n*log(n)) 0 no
  811. 'mergesort' 2 O(n*log(n)) ~n/2 yes
  812. 'timsort' 2 O(n*log(n)) ~n/2 yes
  813. =========== ======= ============= ============ ========
  814. .. note:: The datatype determines which of 'mergesort' or 'timsort'
  815. is actually used, even if 'mergesort' is specified. User selection
  816. at a finer scale is not currently available.
  817. For performance, ``sort`` makes a temporary copy if needed to make the data
  818. `contiguous <https://numpy.org/doc/stable/glossary.html#term-contiguous>`_
  819. in memory along the sort axis. For even better performance and reduced
  820. memory consumption, ensure that the array is already contiguous along the
  821. sort axis.
  822. The sort order for complex numbers is lexicographic. If both the real
  823. and imaginary parts are non-nan then the order is determined by the
  824. real parts except when they are equal, in which case the order is
  825. determined by the imaginary parts.
  826. Previous to numpy 1.4.0 sorting real and complex arrays containing nan
  827. values led to undefined behaviour. In numpy versions >= 1.4.0 nan
  828. values are sorted to the end. The extended sort order is:
  829. * Real: [R, nan]
  830. * Complex: [R + Rj, R + nanj, nan + Rj, nan + nanj]
  831. where R is a non-nan real value. Complex values with the same nan
  832. placements are sorted according to the non-nan part if it exists.
  833. Non-nan values are sorted as before.
  834. quicksort has been changed to:
  835. `introsort <https://en.wikipedia.org/wiki/Introsort>`_.
  836. When sorting does not make enough progress it switches to
  837. `heapsort <https://en.wikipedia.org/wiki/Heapsort>`_.
  838. This implementation makes quicksort O(n*log(n)) in the worst case.
  839. 'stable' automatically chooses the best stable sorting algorithm
  840. for the data type being sorted.
  841. It, along with 'mergesort' is currently mapped to
  842. `timsort <https://en.wikipedia.org/wiki/Timsort>`_
  843. or `radix sort <https://en.wikipedia.org/wiki/Radix_sort>`_
  844. depending on the data type.
  845. API forward compatibility currently limits the
  846. ability to select the implementation and it is hardwired for the different
  847. data types.
  848. Timsort is added for better performance on already or nearly
  849. sorted data. On random data timsort is almost identical to
  850. mergesort. It is now used for stable sort while quicksort is still the
  851. default sort if none is chosen. For timsort details, refer to
  852. `CPython listsort.txt
  853. <https://github.com/python/cpython/blob/3.7/Objects/listsort.txt>`_
  854. 'mergesort' and 'stable' are mapped to radix sort for integer data types.
  855. Radix sort is an O(n) sort instead of O(n log n).
  856. NaT now sorts to the end of arrays for consistency with NaN.
  857. Examples
  858. --------
  859. >>> import numpy as np
  860. >>> a = np.array([[1,4],[3,1]])
  861. >>> np.sort(a) # sort along the last axis
  862. array([[1, 4],
  863. [1, 3]])
  864. >>> np.sort(a, axis=None) # sort the flattened array
  865. array([1, 1, 3, 4])
  866. >>> np.sort(a, axis=0) # sort along the first axis
  867. array([[1, 1],
  868. [3, 4]])
  869. Use the `order` keyword to specify a field to use when sorting a
  870. structured array:
  871. >>> dtype = [('name', 'S10'), ('height', float), ('age', int)]
  872. >>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38),
  873. ... ('Galahad', 1.7, 38)]
  874. >>> a = np.array(values, dtype=dtype) # create a structured array
  875. >>> np.sort(a, order='height') # doctest: +SKIP
  876. array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41),
  877. ('Lancelot', 1.8999999999999999, 38)],
  878. dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
  879. Sort by age, then height if ages are equal:
  880. >>> np.sort(a, order=['age', 'height']) # doctest: +SKIP
  881. array([('Galahad', 1.7, 38), ('Lancelot', 1.8999999999999999, 38),
  882. ('Arthur', 1.8, 41)],
  883. dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
  884. """
  885. if axis is None:
  886. # flatten returns (1, N) for np.matrix, so always use the last axis
  887. a = asanyarray(a).flatten()
  888. axis = -1
  889. else:
  890. a = asanyarray(a).copy(order="K")
  891. a.sort(axis=axis, kind=kind, order=order, stable=stable)
  892. return a
  893. def _argsort_dispatcher(a, axis=None, kind=None, order=None, *, stable=None):
  894. return (a,)
  895. @array_function_dispatch(_argsort_dispatcher)
  896. def argsort(a, axis=-1, kind=None, order=None, *, stable=None):
  897. """
  898. Returns the indices that would sort an array.
  899. Perform an indirect sort along the given axis using the algorithm specified
  900. by the `kind` keyword. It returns an array of indices of the same shape as
  901. `a` that index data along the given axis in sorted order.
  902. Parameters
  903. ----------
  904. a : array_like
  905. Array to sort.
  906. axis : int or None, optional
  907. Axis along which to sort. The default is -1 (the last axis). If None,
  908. the flattened array is used.
  909. kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
  910. Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
  911. and 'mergesort' use timsort under the covers and, in general, the
  912. actual implementation will vary with data type. The 'mergesort' option
  913. is retained for backwards compatibility.
  914. order : str or list of str, optional
  915. When `a` is an array with fields defined, this argument specifies
  916. which fields to compare first, second, etc. A single field can
  917. be specified as a string, and not all fields need be specified,
  918. but unspecified fields will still be used, in the order in which
  919. they come up in the dtype, to break ties.
  920. stable : bool, optional
  921. Sort stability. If ``True``, the returned array will maintain
  922. the relative order of ``a`` values which compare as equal.
  923. If ``False`` or ``None``, this is not guaranteed. Internally,
  924. this option selects ``kind='stable'``. Default: ``None``.
  925. .. versionadded:: 2.0.0
  926. Returns
  927. -------
  928. index_array : ndarray, int
  929. Array of indices that sort `a` along the specified `axis`.
  930. If `a` is one-dimensional, ``a[index_array]`` yields a sorted `a`.
  931. More generally, ``np.take_along_axis(a, index_array, axis=axis)``
  932. always yields the sorted `a`, irrespective of dimensionality.
  933. See Also
  934. --------
  935. sort : Describes sorting algorithms used.
  936. lexsort : Indirect stable sort with multiple keys.
  937. ndarray.sort : Inplace sort.
  938. argpartition : Indirect partial sort.
  939. take_along_axis : Apply ``index_array`` from argsort
  940. to an array as if by calling sort.
  941. Notes
  942. -----
  943. See `sort` for notes on the different sorting algorithms.
  944. As of NumPy 1.4.0 `argsort` works with real/complex arrays containing
  945. nan values. The enhanced sort order is documented in `sort`.
  946. Examples
  947. --------
  948. One dimensional array:
  949. >>> import numpy as np
  950. >>> x = np.array([3, 1, 2])
  951. >>> np.argsort(x)
  952. array([1, 2, 0])
  953. Two-dimensional array:
  954. >>> x = np.array([[0, 3], [2, 2]])
  955. >>> x
  956. array([[0, 3],
  957. [2, 2]])
  958. >>> ind = np.argsort(x, axis=0) # sorts along first axis (down)
  959. >>> ind
  960. array([[0, 1],
  961. [1, 0]])
  962. >>> np.take_along_axis(x, ind, axis=0) # same as np.sort(x, axis=0)
  963. array([[0, 2],
  964. [2, 3]])
  965. >>> ind = np.argsort(x, axis=1) # sorts along last axis (across)
  966. >>> ind
  967. array([[0, 1],
  968. [0, 1]])
  969. >>> np.take_along_axis(x, ind, axis=1) # same as np.sort(x, axis=1)
  970. array([[0, 3],
  971. [2, 2]])
  972. Indices of the sorted elements of a N-dimensional array:
  973. >>> ind = np.unravel_index(np.argsort(x, axis=None), x.shape)
  974. >>> ind
  975. (array([0, 1, 1, 0]), array([0, 0, 1, 1]))
  976. >>> x[ind] # same as np.sort(x, axis=None)
  977. array([0, 2, 2, 3])
  978. Sorting with keys:
  979. >>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')])
  980. >>> x
  981. array([(1, 0), (0, 1)],
  982. dtype=[('x', '<i4'), ('y', '<i4')])
  983. >>> np.argsort(x, order=('x','y'))
  984. array([1, 0])
  985. >>> np.argsort(x, order=('y','x'))
  986. array([0, 1])
  987. """
  988. return _wrapfunc(
  989. a, 'argsort', axis=axis, kind=kind, order=order, stable=stable
  990. )
  991. def _argmax_dispatcher(a, axis=None, out=None, *, keepdims=np._NoValue):
  992. return (a, out)
  993. @array_function_dispatch(_argmax_dispatcher)
  994. def argmax(a, axis=None, out=None, *, keepdims=np._NoValue):
  995. """
  996. Returns the indices of the maximum values along an axis.
  997. Parameters
  998. ----------
  999. a : array_like
  1000. Input array.
  1001. axis : int, optional
  1002. By default, the index is into the flattened array, otherwise
  1003. along the specified axis.
  1004. out : array, optional
  1005. If provided, the result will be inserted into this array. It should
  1006. be of the appropriate shape and dtype.
  1007. keepdims : bool, optional
  1008. If this is set to True, the axes which are reduced are left
  1009. in the result as dimensions with size one. With this option,
  1010. the result will broadcast correctly against the array.
  1011. .. versionadded:: 1.22.0
  1012. Returns
  1013. -------
  1014. index_array : ndarray of ints
  1015. Array of indices into the array. It has the same shape as ``a.shape``
  1016. with the dimension along `axis` removed. If `keepdims` is set to True,
  1017. then the size of `axis` will be 1 with the resulting array having same
  1018. shape as ``a.shape``.
  1019. See Also
  1020. --------
  1021. ndarray.argmax, argmin
  1022. amax : The maximum value along a given axis.
  1023. unravel_index : Convert a flat index into an index tuple.
  1024. take_along_axis : Apply ``np.expand_dims(index_array, axis)``
  1025. from argmax to an array as if by calling max.
  1026. Notes
  1027. -----
  1028. In case of multiple occurrences of the maximum values, the indices
  1029. corresponding to the first occurrence are returned.
  1030. Examples
  1031. --------
  1032. >>> import numpy as np
  1033. >>> a = np.arange(6).reshape(2,3) + 10
  1034. >>> a
  1035. array([[10, 11, 12],
  1036. [13, 14, 15]])
  1037. >>> np.argmax(a)
  1038. 5
  1039. >>> np.argmax(a, axis=0)
  1040. array([1, 1, 1])
  1041. >>> np.argmax(a, axis=1)
  1042. array([2, 2])
  1043. Indexes of the maximal elements of a N-dimensional array:
  1044. >>> a.flat[np.argmax(a)]
  1045. 15
  1046. >>> ind = np.unravel_index(np.argmax(a, axis=None), a.shape)
  1047. >>> ind
  1048. (1, 2)
  1049. >>> a[ind]
  1050. 15
  1051. >>> b = np.arange(6)
  1052. >>> b[1] = 5
  1053. >>> b
  1054. array([0, 5, 2, 3, 4, 5])
  1055. >>> np.argmax(b) # Only the first occurrence is returned.
  1056. 1
  1057. >>> x = np.array([[4,2,3], [1,0,3]])
  1058. >>> index_array = np.argmax(x, axis=-1)
  1059. >>> # Same as np.amax(x, axis=-1, keepdims=True)
  1060. >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)
  1061. array([[4],
  1062. [3]])
  1063. >>> # Same as np.amax(x, axis=-1)
  1064. >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1),
  1065. ... axis=-1).squeeze(axis=-1)
  1066. array([4, 3])
  1067. Setting `keepdims` to `True`,
  1068. >>> x = np.arange(24).reshape((2, 3, 4))
  1069. >>> res = np.argmax(x, axis=1, keepdims=True)
  1070. >>> res.shape
  1071. (2, 1, 4)
  1072. """
  1073. kwds = {'keepdims': keepdims} if keepdims is not np._NoValue else {}
  1074. return _wrapfunc(a, 'argmax', axis=axis, out=out, **kwds)
  1075. def _argmin_dispatcher(a, axis=None, out=None, *, keepdims=np._NoValue):
  1076. return (a, out)
  1077. @array_function_dispatch(_argmin_dispatcher)
  1078. def argmin(a, axis=None, out=None, *, keepdims=np._NoValue):
  1079. """
  1080. Returns the indices of the minimum values along an axis.
  1081. Parameters
  1082. ----------
  1083. a : array_like
  1084. Input array.
  1085. axis : int, optional
  1086. By default, the index is into the flattened array, otherwise
  1087. along the specified axis.
  1088. out : array, optional
  1089. If provided, the result will be inserted into this array. It should
  1090. be of the appropriate shape and dtype.
  1091. keepdims : bool, optional
  1092. If this is set to True, the axes which are reduced are left
  1093. in the result as dimensions with size one. With this option,
  1094. the result will broadcast correctly against the array.
  1095. .. versionadded:: 1.22.0
  1096. Returns
  1097. -------
  1098. index_array : ndarray of ints
  1099. Array of indices into the array. It has the same shape as `a.shape`
  1100. with the dimension along `axis` removed. If `keepdims` is set to True,
  1101. then the size of `axis` will be 1 with the resulting array having same
  1102. shape as `a.shape`.
  1103. See Also
  1104. --------
  1105. ndarray.argmin, argmax
  1106. amin : The minimum value along a given axis.
  1107. unravel_index : Convert a flat index into an index tuple.
  1108. take_along_axis : Apply ``np.expand_dims(index_array, axis)``
  1109. from argmin to an array as if by calling min.
  1110. Notes
  1111. -----
  1112. In case of multiple occurrences of the minimum values, the indices
  1113. corresponding to the first occurrence are returned.
  1114. Examples
  1115. --------
  1116. >>> import numpy as np
  1117. >>> a = np.arange(6).reshape(2,3) + 10
  1118. >>> a
  1119. array([[10, 11, 12],
  1120. [13, 14, 15]])
  1121. >>> np.argmin(a)
  1122. 0
  1123. >>> np.argmin(a, axis=0)
  1124. array([0, 0, 0])
  1125. >>> np.argmin(a, axis=1)
  1126. array([0, 0])
  1127. Indices of the minimum elements of a N-dimensional array:
  1128. >>> a.flat[np.argmin(a)]
  1129. 10
  1130. >>> ind = np.unravel_index(np.argmin(a, axis=None), a.shape)
  1131. >>> ind
  1132. (0, 0)
  1133. >>> a[ind]
  1134. 10
  1135. >>> b = np.arange(6) + 10
  1136. >>> b[4] = 10
  1137. >>> b
  1138. array([10, 11, 12, 13, 10, 15])
  1139. >>> np.argmin(b) # Only the first occurrence is returned.
  1140. 0
  1141. >>> x = np.array([[4,2,3], [1,0,3]])
  1142. >>> index_array = np.argmin(x, axis=-1)
  1143. >>> # Same as np.amin(x, axis=-1, keepdims=True)
  1144. >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)
  1145. array([[2],
  1146. [0]])
  1147. >>> # Same as np.amax(x, axis=-1)
  1148. >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1),
  1149. ... axis=-1).squeeze(axis=-1)
  1150. array([2, 0])
  1151. Setting `keepdims` to `True`,
  1152. >>> x = np.arange(24).reshape((2, 3, 4))
  1153. >>> res = np.argmin(x, axis=1, keepdims=True)
  1154. >>> res.shape
  1155. (2, 1, 4)
  1156. """
  1157. kwds = {'keepdims': keepdims} if keepdims is not np._NoValue else {}
  1158. return _wrapfunc(a, 'argmin', axis=axis, out=out, **kwds)
  1159. def _searchsorted_dispatcher(a, v, side=None, sorter=None):
  1160. return (a, v, sorter)
  1161. @array_function_dispatch(_searchsorted_dispatcher)
  1162. def searchsorted(a, v, side='left', sorter=None):
  1163. """
  1164. Find indices where elements should be inserted to maintain order.
  1165. Find the indices into a sorted array `a` such that, if the
  1166. corresponding elements in `v` were inserted before the indices, the
  1167. order of `a` would be preserved.
  1168. Assuming that `a` is sorted:
  1169. ====== ============================
  1170. `side` returned index `i` satisfies
  1171. ====== ============================
  1172. left ``a[i-1] < v <= a[i]``
  1173. right ``a[i-1] <= v < a[i]``
  1174. ====== ============================
  1175. Parameters
  1176. ----------
  1177. a : 1-D array_like
  1178. Input array. If `sorter` is None, then it must be sorted in
  1179. ascending order, otherwise `sorter` must be an array of indices
  1180. that sort it.
  1181. v : array_like
  1182. Values to insert into `a`.
  1183. side : {'left', 'right'}, optional
  1184. If 'left', the index of the first suitable location found is given.
  1185. If 'right', return the last such index. If there is no suitable
  1186. index, return either 0 or N (where N is the length of `a`).
  1187. sorter : 1-D array_like, optional
  1188. Optional array of integer indices that sort array a into ascending
  1189. order. They are typically the result of argsort.
  1190. Returns
  1191. -------
  1192. indices : int or array of ints
  1193. Array of insertion points with the same shape as `v`,
  1194. or an integer if `v` is a scalar.
  1195. See Also
  1196. --------
  1197. sort : Return a sorted copy of an array.
  1198. histogram : Produce histogram from 1-D data.
  1199. Notes
  1200. -----
  1201. Binary search is used to find the required insertion points.
  1202. As of NumPy 1.4.0 `searchsorted` works with real/complex arrays containing
  1203. `nan` values. The enhanced sort order is documented in `sort`.
  1204. This function uses the same algorithm as the builtin python
  1205. `bisect.bisect_left` (``side='left'``) and `bisect.bisect_right`
  1206. (``side='right'``) functions, which is also vectorized
  1207. in the `v` argument.
  1208. Examples
  1209. --------
  1210. >>> import numpy as np
  1211. >>> np.searchsorted([11,12,13,14,15], 13)
  1212. 2
  1213. >>> np.searchsorted([11,12,13,14,15], 13, side='right')
  1214. 3
  1215. >>> np.searchsorted([11,12,13,14,15], [-10, 20, 12, 13])
  1216. array([0, 5, 1, 2])
  1217. When `sorter` is used, the returned indices refer to the sorted
  1218. array of `a` and not `a` itself:
  1219. >>> a = np.array([40, 10, 20, 30])
  1220. >>> sorter = np.argsort(a)
  1221. >>> sorter
  1222. array([1, 2, 3, 0]) # Indices that would sort the array 'a'
  1223. >>> result = np.searchsorted(a, 25, sorter=sorter)
  1224. >>> result
  1225. 2
  1226. >>> a[sorter[result]]
  1227. 30 # The element at index 2 of the sorted array is 30.
  1228. """
  1229. return _wrapfunc(a, 'searchsorted', v, side=side, sorter=sorter)
  1230. def _resize_dispatcher(a, new_shape):
  1231. return (a,)
  1232. @array_function_dispatch(_resize_dispatcher)
  1233. def resize(a, new_shape):
  1234. """
  1235. Return a new array with the specified shape.
  1236. If the new array is larger than the original array, then the new
  1237. array is filled with repeated copies of `a`. Note that this behavior
  1238. is different from a.resize(new_shape) which fills with zeros instead
  1239. of repeated copies of `a`.
  1240. Parameters
  1241. ----------
  1242. a : array_like
  1243. Array to be resized.
  1244. new_shape : int or tuple of int
  1245. Shape of resized array.
  1246. Returns
  1247. -------
  1248. reshaped_array : ndarray
  1249. The new array is formed from the data in the old array, repeated
  1250. if necessary to fill out the required number of elements. The
  1251. data are repeated iterating over the array in C-order.
  1252. See Also
  1253. --------
  1254. numpy.reshape : Reshape an array without changing the total size.
  1255. numpy.pad : Enlarge and pad an array.
  1256. numpy.repeat : Repeat elements of an array.
  1257. ndarray.resize : resize an array in-place.
  1258. Notes
  1259. -----
  1260. When the total size of the array does not change `~numpy.reshape` should
  1261. be used. In most other cases either indexing (to reduce the size)
  1262. or padding (to increase the size) may be a more appropriate solution.
  1263. Warning: This functionality does **not** consider axes separately,
  1264. i.e. it does not apply interpolation/extrapolation.
  1265. It fills the return array with the required number of elements, iterating
  1266. over `a` in C-order, disregarding axes (and cycling back from the start if
  1267. the new shape is larger). This functionality is therefore not suitable to
  1268. resize images, or data where each axis represents a separate and distinct
  1269. entity.
  1270. Examples
  1271. --------
  1272. >>> import numpy as np
  1273. >>> a = np.array([[0,1],[2,3]])
  1274. >>> np.resize(a,(2,3))
  1275. array([[0, 1, 2],
  1276. [3, 0, 1]])
  1277. >>> np.resize(a,(1,4))
  1278. array([[0, 1, 2, 3]])
  1279. >>> np.resize(a,(2,4))
  1280. array([[0, 1, 2, 3],
  1281. [0, 1, 2, 3]])
  1282. """
  1283. if isinstance(new_shape, (int, nt.integer)):
  1284. new_shape = (new_shape,)
  1285. a = ravel(a)
  1286. new_size = 1
  1287. for dim_length in new_shape:
  1288. new_size *= dim_length
  1289. if dim_length < 0:
  1290. raise ValueError(
  1291. 'all elements of `new_shape` must be non-negative'
  1292. )
  1293. if a.size == 0 or new_size == 0:
  1294. # First case must zero fill. The second would have repeats == 0.
  1295. return np.zeros_like(a, shape=new_shape)
  1296. # ceiling division without negating new_size
  1297. repeats = (new_size + a.size - 1) // a.size
  1298. a = concatenate((a,) * repeats)[:new_size]
  1299. return reshape(a, new_shape)
  1300. def _squeeze_dispatcher(a, axis=None):
  1301. return (a,)
  1302. @array_function_dispatch(_squeeze_dispatcher)
  1303. def squeeze(a, axis=None):
  1304. """
  1305. Remove axes of length one from `a`.
  1306. Parameters
  1307. ----------
  1308. a : array_like
  1309. Input data.
  1310. axis : None or int or tuple of ints, optional
  1311. Selects a subset of the entries of length one in the
  1312. shape. If an axis is selected with shape entry greater than
  1313. one, an error is raised.
  1314. Returns
  1315. -------
  1316. squeezed : ndarray
  1317. The input array, but with all or a subset of the
  1318. dimensions of length 1 removed. This is always `a` itself
  1319. or a view into `a`. Note that if all axes are squeezed,
  1320. the result is a 0d array and not a scalar.
  1321. Raises
  1322. ------
  1323. ValueError
  1324. If `axis` is not None, and an axis being squeezed is not of length 1
  1325. See Also
  1326. --------
  1327. expand_dims : The inverse operation, adding entries of length one
  1328. reshape : Insert, remove, and combine dimensions, and resize existing ones
  1329. Examples
  1330. --------
  1331. >>> import numpy as np
  1332. >>> x = np.array([[[0], [1], [2]]])
  1333. >>> x.shape
  1334. (1, 3, 1)
  1335. >>> np.squeeze(x).shape
  1336. (3,)
  1337. >>> np.squeeze(x, axis=0).shape
  1338. (3, 1)
  1339. >>> np.squeeze(x, axis=1).shape
  1340. Traceback (most recent call last):
  1341. ...
  1342. ValueError: cannot select an axis to squeeze out which has size
  1343. not equal to one
  1344. >>> np.squeeze(x, axis=2).shape
  1345. (1, 3)
  1346. >>> x = np.array([[1234]])
  1347. >>> x.shape
  1348. (1, 1)
  1349. >>> np.squeeze(x)
  1350. array(1234) # 0d array
  1351. >>> np.squeeze(x).shape
  1352. ()
  1353. >>> np.squeeze(x)[()]
  1354. 1234
  1355. """
  1356. try:
  1357. squeeze = a.squeeze
  1358. except AttributeError:
  1359. return _wrapit(a, 'squeeze', axis=axis)
  1360. if axis is None:
  1361. return squeeze()
  1362. else:
  1363. return squeeze(axis=axis)
  1364. def _diagonal_dispatcher(a, offset=None, axis1=None, axis2=None):
  1365. return (a,)
  1366. @array_function_dispatch(_diagonal_dispatcher)
  1367. def diagonal(a, offset=0, axis1=0, axis2=1):
  1368. """
  1369. Return specified diagonals.
  1370. If `a` is 2-D, returns the diagonal of `a` with the given offset,
  1371. i.e., the collection of elements of the form ``a[i, i+offset]``. If
  1372. `a` has more than two dimensions, then the axes specified by `axis1`
  1373. and `axis2` are used to determine the 2-D sub-array whose diagonal is
  1374. returned. The shape of the resulting array can be determined by
  1375. removing `axis1` and `axis2` and appending an index to the right equal
  1376. to the size of the resulting diagonals.
  1377. In versions of NumPy prior to 1.7, this function always returned a new,
  1378. independent array containing a copy of the values in the diagonal.
  1379. In NumPy 1.7 and 1.8, it continues to return a copy of the diagonal,
  1380. but depending on this fact is deprecated. Writing to the resulting
  1381. array continues to work as it used to, but a FutureWarning is issued.
  1382. Starting in NumPy 1.9 it returns a read-only view on the original array.
  1383. Attempting to write to the resulting array will produce an error.
  1384. In some future release, it will return a read/write view and writing to
  1385. the returned array will alter your original array. The returned array
  1386. will have the same type as the input array.
  1387. If you don't write to the array returned by this function, then you can
  1388. just ignore all of the above.
  1389. If you depend on the current behavior, then we suggest copying the
  1390. returned array explicitly, i.e., use ``np.diagonal(a).copy()`` instead
  1391. of just ``np.diagonal(a)``. This will work with both past and future
  1392. versions of NumPy.
  1393. Parameters
  1394. ----------
  1395. a : array_like
  1396. Array from which the diagonals are taken.
  1397. offset : int, optional
  1398. Offset of the diagonal from the main diagonal. Can be positive or
  1399. negative. Defaults to main diagonal (0).
  1400. axis1 : int, optional
  1401. Axis to be used as the first axis of the 2-D sub-arrays from which
  1402. the diagonals should be taken. Defaults to first axis (0).
  1403. axis2 : int, optional
  1404. Axis to be used as the second axis of the 2-D sub-arrays from
  1405. which the diagonals should be taken. Defaults to second axis (1).
  1406. Returns
  1407. -------
  1408. array_of_diagonals : ndarray
  1409. If `a` is 2-D, then a 1-D array containing the diagonal and of the
  1410. same type as `a` is returned unless `a` is a `matrix`, in which case
  1411. a 1-D array rather than a (2-D) `matrix` is returned in order to
  1412. maintain backward compatibility.
  1413. If ``a.ndim > 2``, then the dimensions specified by `axis1` and `axis2`
  1414. are removed, and a new axis inserted at the end corresponding to the
  1415. diagonal.
  1416. Raises
  1417. ------
  1418. ValueError
  1419. If the dimension of `a` is less than 2.
  1420. See Also
  1421. --------
  1422. diag : MATLAB work-a-like for 1-D and 2-D arrays.
  1423. diagflat : Create diagonal arrays.
  1424. trace : Sum along diagonals.
  1425. Examples
  1426. --------
  1427. >>> import numpy as np
  1428. >>> a = np.arange(4).reshape(2,2)
  1429. >>> a
  1430. array([[0, 1],
  1431. [2, 3]])
  1432. >>> a.diagonal()
  1433. array([0, 3])
  1434. >>> a.diagonal(1)
  1435. array([1])
  1436. A 3-D example:
  1437. >>> a = np.arange(8).reshape(2,2,2); a
  1438. array([[[0, 1],
  1439. [2, 3]],
  1440. [[4, 5],
  1441. [6, 7]]])
  1442. >>> a.diagonal(0, # Main diagonals of two arrays created by skipping
  1443. ... 0, # across the outer(left)-most axis last and
  1444. ... 1) # the "middle" (row) axis first.
  1445. array([[0, 6],
  1446. [1, 7]])
  1447. The sub-arrays whose main diagonals we just obtained; note that each
  1448. corresponds to fixing the right-most (column) axis, and that the
  1449. diagonals are "packed" in rows.
  1450. >>> a[:,:,0] # main diagonal is [0 6]
  1451. array([[0, 2],
  1452. [4, 6]])
  1453. >>> a[:,:,1] # main diagonal is [1 7]
  1454. array([[1, 3],
  1455. [5, 7]])
  1456. The anti-diagonal can be obtained by reversing the order of elements
  1457. using either `numpy.flipud` or `numpy.fliplr`.
  1458. >>> a = np.arange(9).reshape(3, 3)
  1459. >>> a
  1460. array([[0, 1, 2],
  1461. [3, 4, 5],
  1462. [6, 7, 8]])
  1463. >>> np.fliplr(a).diagonal() # Horizontal flip
  1464. array([2, 4, 6])
  1465. >>> np.flipud(a).diagonal() # Vertical flip
  1466. array([6, 4, 2])
  1467. Note that the order in which the diagonal is retrieved varies depending
  1468. on the flip function.
  1469. """
  1470. if isinstance(a, np.matrix):
  1471. # Make diagonal of matrix 1-D to preserve backward compatibility.
  1472. return asarray(a).diagonal(offset=offset, axis1=axis1, axis2=axis2)
  1473. else:
  1474. return asanyarray(a).diagonal(offset=offset, axis1=axis1, axis2=axis2)
  1475. def _trace_dispatcher(
  1476. a, offset=None, axis1=None, axis2=None, dtype=None, out=None):
  1477. return (a, out)
  1478. @array_function_dispatch(_trace_dispatcher)
  1479. def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
  1480. """
  1481. Return the sum along diagonals of the array.
  1482. If `a` is 2-D, the sum along its diagonal with the given offset
  1483. is returned, i.e., the sum of elements ``a[i,i+offset]`` for all i.
  1484. If `a` has more than two dimensions, then the axes specified by axis1 and
  1485. axis2 are used to determine the 2-D sub-arrays whose traces are returned.
  1486. The shape of the resulting array is the same as that of `a` with `axis1`
  1487. and `axis2` removed.
  1488. Parameters
  1489. ----------
  1490. a : array_like
  1491. Input array, from which the diagonals are taken.
  1492. offset : int, optional
  1493. Offset of the diagonal from the main diagonal. Can be both positive
  1494. and negative. Defaults to 0.
  1495. axis1, axis2 : int, optional
  1496. Axes to be used as the first and second axis of the 2-D sub-arrays
  1497. from which the diagonals should be taken. Defaults are the first two
  1498. axes of `a`.
  1499. dtype : dtype, optional
  1500. Determines the data-type of the returned array and of the accumulator
  1501. where the elements are summed. If dtype has the value None and `a` is
  1502. of integer type of precision less than the default integer
  1503. precision, then the default integer precision is used. Otherwise,
  1504. the precision is the same as that of `a`.
  1505. out : ndarray, optional
  1506. Array into which the output is placed. Its type is preserved and
  1507. it must be of the right shape to hold the output.
  1508. Returns
  1509. -------
  1510. sum_along_diagonals : ndarray
  1511. If `a` is 2-D, the sum along the diagonal is returned. If `a` has
  1512. larger dimensions, then an array of sums along diagonals is returned.
  1513. See Also
  1514. --------
  1515. diag, diagonal, diagflat
  1516. Examples
  1517. --------
  1518. >>> import numpy as np
  1519. >>> np.trace(np.eye(3))
  1520. 3.0
  1521. >>> a = np.arange(8).reshape((2,2,2))
  1522. >>> np.trace(a)
  1523. array([6, 8])
  1524. >>> a = np.arange(24).reshape((2,2,2,3))
  1525. >>> np.trace(a).shape
  1526. (2, 3)
  1527. """
  1528. if isinstance(a, np.matrix):
  1529. # Get trace of matrix via an array to preserve backward compatibility.
  1530. return asarray(a).trace(
  1531. offset=offset, axis1=axis1, axis2=axis2, dtype=dtype, out=out
  1532. )
  1533. else:
  1534. return asanyarray(a).trace(
  1535. offset=offset, axis1=axis1, axis2=axis2, dtype=dtype, out=out
  1536. )
  1537. def _ravel_dispatcher(a, order=None):
  1538. return (a,)
  1539. @array_function_dispatch(_ravel_dispatcher)
  1540. def ravel(a, order='C'):
  1541. """Return a contiguous flattened array.
  1542. A 1-D array, containing the elements of the input, is returned. A copy is
  1543. made only if needed.
  1544. As of NumPy 1.10, the returned array will have the same type as the input
  1545. array. (for example, a masked array will be returned for a masked array
  1546. input)
  1547. Parameters
  1548. ----------
  1549. a : array_like
  1550. Input array. The elements in `a` are read in the order specified by
  1551. `order`, and packed as a 1-D array.
  1552. order : {'C','F', 'A', 'K'}, optional
  1553. The elements of `a` are read using this index order. 'C' means
  1554. to index the elements in row-major, C-style order,
  1555. with the last axis index changing fastest, back to the first
  1556. axis index changing slowest. 'F' means to index the elements
  1557. in column-major, Fortran-style order, with the
  1558. first index changing fastest, and the last index changing
  1559. slowest. Note that the 'C' and 'F' options take no account of
  1560. the memory layout of the underlying array, and only refer to
  1561. the order of axis indexing. 'A' means to read the elements in
  1562. Fortran-like index order if `a` is Fortran *contiguous* in
  1563. memory, C-like order otherwise. 'K' means to read the
  1564. elements in the order they occur in memory, except for
  1565. reversing the data when strides are negative. By default, 'C'
  1566. index order is used.
  1567. Returns
  1568. -------
  1569. y : array_like
  1570. y is a contiguous 1-D array of the same subtype as `a`,
  1571. with shape ``(a.size,)``.
  1572. Note that matrices are special cased for backward compatibility,
  1573. if `a` is a matrix, then y is a 1-D ndarray.
  1574. See Also
  1575. --------
  1576. ndarray.flat : 1-D iterator over an array.
  1577. ndarray.flatten : 1-D array copy of the elements of an array
  1578. in row-major order.
  1579. ndarray.reshape : Change the shape of an array without changing its data.
  1580. Notes
  1581. -----
  1582. In row-major, C-style order, in two dimensions, the row index
  1583. varies the slowest, and the column index the quickest. This can
  1584. be generalized to multiple dimensions, where row-major order
  1585. implies that the index along the first axis varies slowest, and
  1586. the index along the last quickest. The opposite holds for
  1587. column-major, Fortran-style index ordering.
  1588. When a view is desired in as many cases as possible, ``arr.reshape(-1)``
  1589. may be preferable. However, ``ravel`` supports ``K`` in the optional
  1590. ``order`` argument while ``reshape`` does not.
  1591. Examples
  1592. --------
  1593. It is equivalent to ``reshape(-1, order=order)``.
  1594. >>> import numpy as np
  1595. >>> x = np.array([[1, 2, 3], [4, 5, 6]])
  1596. >>> np.ravel(x)
  1597. array([1, 2, 3, 4, 5, 6])
  1598. >>> x.reshape(-1)
  1599. array([1, 2, 3, 4, 5, 6])
  1600. >>> np.ravel(x, order='F')
  1601. array([1, 4, 2, 5, 3, 6])
  1602. When ``order`` is 'A', it will preserve the array's 'C' or 'F' ordering:
  1603. >>> np.ravel(x.T)
  1604. array([1, 4, 2, 5, 3, 6])
  1605. >>> np.ravel(x.T, order='A')
  1606. array([1, 2, 3, 4, 5, 6])
  1607. When ``order`` is 'K', it will preserve orderings that are neither 'C'
  1608. nor 'F', but won't reverse axes:
  1609. >>> a = np.arange(3)[::-1]; a
  1610. array([2, 1, 0])
  1611. >>> a.ravel(order='C')
  1612. array([2, 1, 0])
  1613. >>> a.ravel(order='K')
  1614. array([2, 1, 0])
  1615. >>> a = np.arange(12).reshape(2,3,2).swapaxes(1,2); a
  1616. array([[[ 0, 2, 4],
  1617. [ 1, 3, 5]],
  1618. [[ 6, 8, 10],
  1619. [ 7, 9, 11]]])
  1620. >>> a.ravel(order='C')
  1621. array([ 0, 2, 4, 1, 3, 5, 6, 8, 10, 7, 9, 11])
  1622. >>> a.ravel(order='K')
  1623. array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
  1624. """
  1625. if isinstance(a, np.matrix):
  1626. return asarray(a).ravel(order=order)
  1627. else:
  1628. return asanyarray(a).ravel(order=order)
  1629. def _nonzero_dispatcher(a):
  1630. return (a,)
  1631. @array_function_dispatch(_nonzero_dispatcher)
  1632. def nonzero(a):
  1633. """
  1634. Return the indices of the elements that are non-zero.
  1635. Returns a tuple of arrays, one for each dimension of `a`,
  1636. containing the indices of the non-zero elements in that
  1637. dimension. The values in `a` are always tested and returned in
  1638. row-major, C-style order.
  1639. To group the indices by element, rather than dimension, use `argwhere`,
  1640. which returns a row for each non-zero element.
  1641. Parameters
  1642. ----------
  1643. a : array_like
  1644. Input array.
  1645. Returns
  1646. -------
  1647. tuple_of_arrays : tuple
  1648. Indices of elements that are non-zero.
  1649. See Also
  1650. --------
  1651. flatnonzero :
  1652. Return indices that are non-zero in the flattened version of the input
  1653. array.
  1654. ndarray.nonzero :
  1655. Equivalent ndarray method.
  1656. count_nonzero :
  1657. Counts the number of non-zero elements in the input array.
  1658. Notes
  1659. -----
  1660. While the nonzero values can be obtained with ``a[nonzero(a)]``, it is
  1661. recommended to use ``x[x.astype(bool)]`` or ``x[x != 0]`` instead, which
  1662. will correctly handle 0-d arrays.
  1663. Examples
  1664. --------
  1665. >>> import numpy as np
  1666. >>> x = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]])
  1667. >>> x
  1668. array([[3, 0, 0],
  1669. [0, 4, 0],
  1670. [5, 6, 0]])
  1671. >>> np.nonzero(x)
  1672. (array([0, 1, 2, 2]), array([0, 1, 0, 1]))
  1673. >>> x[np.nonzero(x)]
  1674. array([3, 4, 5, 6])
  1675. >>> np.transpose(np.nonzero(x))
  1676. array([[0, 0],
  1677. [1, 1],
  1678. [2, 0],
  1679. [2, 1]])
  1680. A common use for ``nonzero`` is to find the indices of an array, where
  1681. a condition is True. Given an array `a`, the condition `a` > 3 is a
  1682. boolean array and since False is interpreted as 0, np.nonzero(a > 3)
  1683. yields the indices of the `a` where the condition is true.
  1684. >>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  1685. >>> a > 3
  1686. array([[False, False, False],
  1687. [ True, True, True],
  1688. [ True, True, True]])
  1689. >>> np.nonzero(a > 3)
  1690. (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
  1691. Using this result to index `a` is equivalent to using the mask directly:
  1692. >>> a[np.nonzero(a > 3)]
  1693. array([4, 5, 6, 7, 8, 9])
  1694. >>> a[a > 3] # prefer this spelling
  1695. array([4, 5, 6, 7, 8, 9])
  1696. ``nonzero`` can also be called as a method of the array.
  1697. >>> (a > 3).nonzero()
  1698. (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
  1699. """
  1700. return _wrapfunc(a, 'nonzero')
  1701. def _shape_dispatcher(a):
  1702. return (a,)
  1703. @array_function_dispatch(_shape_dispatcher)
  1704. def shape(a):
  1705. """
  1706. Return the shape of an array.
  1707. Parameters
  1708. ----------
  1709. a : array_like
  1710. Input array.
  1711. Returns
  1712. -------
  1713. shape : tuple of ints
  1714. The elements of the shape tuple give the lengths of the
  1715. corresponding array dimensions.
  1716. See Also
  1717. --------
  1718. len : ``len(a)`` is equivalent to ``np.shape(a)[0]`` for N-D arrays with
  1719. ``N>=1``.
  1720. ndarray.shape : Equivalent array method.
  1721. Examples
  1722. --------
  1723. >>> import numpy as np
  1724. >>> np.shape(np.eye(3))
  1725. (3, 3)
  1726. >>> np.shape([[1, 3]])
  1727. (1, 2)
  1728. >>> np.shape([0])
  1729. (1,)
  1730. >>> np.shape(0)
  1731. ()
  1732. >>> a = np.array([(1, 2), (3, 4), (5, 6)],
  1733. ... dtype=[('x', 'i4'), ('y', 'i4')])
  1734. >>> np.shape(a)
  1735. (3,)
  1736. >>> a.shape
  1737. (3,)
  1738. """
  1739. try:
  1740. result = a.shape
  1741. except AttributeError:
  1742. result = asarray(a).shape
  1743. return result
  1744. def _compress_dispatcher(condition, a, axis=None, out=None):
  1745. return (condition, a, out)
  1746. @array_function_dispatch(_compress_dispatcher)
  1747. def compress(condition, a, axis=None, out=None):
  1748. """
  1749. Return selected slices of an array along given axis.
  1750. When working along a given axis, a slice along that axis is returned in
  1751. `output` for each index where `condition` evaluates to True. When
  1752. working on a 1-D array, `compress` is equivalent to `extract`.
  1753. Parameters
  1754. ----------
  1755. condition : 1-D array of bools
  1756. Array that selects which entries to return. If len(condition)
  1757. is less than the size of `a` along the given axis, then output is
  1758. truncated to the length of the condition array.
  1759. a : array_like
  1760. Array from which to extract a part.
  1761. axis : int, optional
  1762. Axis along which to take slices. If None (default), work on the
  1763. flattened array.
  1764. out : ndarray, optional
  1765. Output array. Its type is preserved and it must be of the right
  1766. shape to hold the output.
  1767. Returns
  1768. -------
  1769. compressed_array : ndarray
  1770. A copy of `a` without the slices along axis for which `condition`
  1771. is false.
  1772. See Also
  1773. --------
  1774. take, choose, diag, diagonal, select
  1775. ndarray.compress : Equivalent method in ndarray
  1776. extract : Equivalent method when working on 1-D arrays
  1777. :ref:`ufuncs-output-type`
  1778. Examples
  1779. --------
  1780. >>> import numpy as np
  1781. >>> a = np.array([[1, 2], [3, 4], [5, 6]])
  1782. >>> a
  1783. array([[1, 2],
  1784. [3, 4],
  1785. [5, 6]])
  1786. >>> np.compress([0, 1], a, axis=0)
  1787. array([[3, 4]])
  1788. >>> np.compress([False, True, True], a, axis=0)
  1789. array([[3, 4],
  1790. [5, 6]])
  1791. >>> np.compress([False, True], a, axis=1)
  1792. array([[2],
  1793. [4],
  1794. [6]])
  1795. Working on the flattened array does not return slices along an axis but
  1796. selects elements.
  1797. >>> np.compress([False, True], a)
  1798. array([2])
  1799. """
  1800. return _wrapfunc(a, 'compress', condition, axis=axis, out=out)
  1801. def _clip_dispatcher(a, a_min=None, a_max=None, out=None, *, min=None,
  1802. max=None, **kwargs):
  1803. return (a, a_min, a_max, out, min, max)
  1804. @array_function_dispatch(_clip_dispatcher)
  1805. def clip(a, a_min=np._NoValue, a_max=np._NoValue, out=None, *,
  1806. min=np._NoValue, max=np._NoValue, **kwargs):
  1807. """
  1808. Clip (limit) the values in an array.
  1809. Given an interval, values outside the interval are clipped to
  1810. the interval edges. For example, if an interval of ``[0, 1]``
  1811. is specified, values smaller than 0 become 0, and values larger
  1812. than 1 become 1.
  1813. Equivalent to but faster than ``np.minimum(a_max, np.maximum(a, a_min))``.
  1814. No check is performed to ensure ``a_min < a_max``.
  1815. Parameters
  1816. ----------
  1817. a : array_like
  1818. Array containing elements to clip.
  1819. a_min, a_max : array_like or None
  1820. Minimum and maximum value. If ``None``, clipping is not performed on
  1821. the corresponding edge. If both ``a_min`` and ``a_max`` are ``None``,
  1822. the elements of the returned array stay the same. Both are broadcasted
  1823. against ``a``.
  1824. out : ndarray, optional
  1825. The results will be placed in this array. It may be the input
  1826. array for in-place clipping. `out` must be of the right shape
  1827. to hold the output. Its type is preserved.
  1828. min, max : array_like or None
  1829. Array API compatible alternatives for ``a_min`` and ``a_max``
  1830. arguments. Either ``a_min`` and ``a_max`` or ``min`` and ``max``
  1831. can be passed at the same time. Default: ``None``.
  1832. .. versionadded:: 2.1.0
  1833. **kwargs
  1834. For other keyword-only arguments, see the
  1835. :ref:`ufunc docs <ufuncs.kwargs>`.
  1836. Returns
  1837. -------
  1838. clipped_array : ndarray
  1839. An array with the elements of `a`, but where values
  1840. < `a_min` are replaced with `a_min`, and those > `a_max`
  1841. with `a_max`.
  1842. See Also
  1843. --------
  1844. :ref:`ufuncs-output-type`
  1845. Notes
  1846. -----
  1847. When `a_min` is greater than `a_max`, `clip` returns an
  1848. array in which all values are equal to `a_max`,
  1849. as shown in the second example.
  1850. Examples
  1851. --------
  1852. >>> import numpy as np
  1853. >>> a = np.arange(10)
  1854. >>> a
  1855. array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  1856. >>> np.clip(a, 1, 8)
  1857. array([1, 1, 2, 3, 4, 5, 6, 7, 8, 8])
  1858. >>> np.clip(a, 8, 1)
  1859. array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
  1860. >>> np.clip(a, 3, 6, out=a)
  1861. array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
  1862. >>> a
  1863. array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
  1864. >>> a = np.arange(10)
  1865. >>> a
  1866. array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  1867. >>> np.clip(a, [3, 4, 1, 1, 1, 4, 4, 4, 4, 4], 8)
  1868. array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8])
  1869. """
  1870. if a_min is np._NoValue and a_max is np._NoValue:
  1871. a_min = None if min is np._NoValue else min
  1872. a_max = None if max is np._NoValue else max
  1873. elif a_min is np._NoValue:
  1874. raise TypeError("clip() missing 1 required positional "
  1875. "argument: 'a_min'")
  1876. elif a_max is np._NoValue:
  1877. raise TypeError("clip() missing 1 required positional "
  1878. "argument: 'a_max'")
  1879. elif min is not np._NoValue or max is not np._NoValue:
  1880. raise ValueError("Passing `min` or `max` keyword argument when "
  1881. "`a_min` and `a_max` are provided is forbidden.")
  1882. return _wrapfunc(a, 'clip', a_min, a_max, out=out, **kwargs)
  1883. def _sum_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None,
  1884. initial=None, where=None):
  1885. return (a, out)
  1886. @array_function_dispatch(_sum_dispatcher)
  1887. def sum(a, axis=None, dtype=None, out=None, keepdims=np._NoValue,
  1888. initial=np._NoValue, where=np._NoValue):
  1889. """
  1890. Sum of array elements over a given axis.
  1891. Parameters
  1892. ----------
  1893. a : array_like
  1894. Elements to sum.
  1895. axis : None or int or tuple of ints, optional
  1896. Axis or axes along which a sum is performed. The default,
  1897. axis=None, will sum all of the elements of the input array. If
  1898. axis is negative it counts from the last to the first axis. If
  1899. axis is a tuple of ints, a sum is performed on all of the axes
  1900. specified in the tuple instead of a single axis or all the axes as
  1901. before.
  1902. dtype : dtype, optional
  1903. The type of the returned array and of the accumulator in which the
  1904. elements are summed. The dtype of `a` is used by default unless `a`
  1905. has an integer dtype of less precision than the default platform
  1906. integer. In that case, if `a` is signed then the platform integer
  1907. is used while if `a` is unsigned then an unsigned integer of the
  1908. same precision as the platform integer is used.
  1909. out : ndarray, optional
  1910. Alternative output array in which to place the result. It must have
  1911. the same shape as the expected output, but the type of the output
  1912. values will be cast if necessary.
  1913. keepdims : bool, optional
  1914. If this is set to True, the axes which are reduced are left
  1915. in the result as dimensions with size one. With this option,
  1916. the result will broadcast correctly against the input array.
  1917. If the default value is passed, then `keepdims` will not be
  1918. passed through to the `sum` method of sub-classes of
  1919. `ndarray`, however any non-default value will be. If the
  1920. sub-class' method does not implement `keepdims` any
  1921. exceptions will be raised.
  1922. initial : scalar, optional
  1923. Starting value for the sum. See `~numpy.ufunc.reduce` for details.
  1924. where : array_like of bool, optional
  1925. Elements to include in the sum. See `~numpy.ufunc.reduce` for details.
  1926. Returns
  1927. -------
  1928. sum_along_axis : ndarray
  1929. An array with the same shape as `a`, with the specified
  1930. axis removed. If `a` is a 0-d array, or if `axis` is None, a scalar
  1931. is returned. If an output array is specified, a reference to
  1932. `out` is returned.
  1933. See Also
  1934. --------
  1935. ndarray.sum : Equivalent method.
  1936. add: ``numpy.add.reduce`` equivalent function.
  1937. cumsum : Cumulative sum of array elements.
  1938. trapezoid : Integration of array values using composite trapezoidal rule.
  1939. mean, average
  1940. Notes
  1941. -----
  1942. Arithmetic is modular when using integer types, and no error is
  1943. raised on overflow.
  1944. The sum of an empty array is the neutral element 0:
  1945. >>> np.sum([])
  1946. 0.0
  1947. For floating point numbers the numerical precision of sum (and
  1948. ``np.add.reduce``) is in general limited by directly adding each number
  1949. individually to the result causing rounding errors in every step.
  1950. However, often numpy will use a numerically better approach (partial
  1951. pairwise summation) leading to improved precision in many use-cases.
  1952. This improved precision is always provided when no ``axis`` is given.
  1953. When ``axis`` is given, it will depend on which axis is summed.
  1954. Technically, to provide the best speed possible, the improved precision
  1955. is only used when the summation is along the fast axis in memory.
  1956. Note that the exact precision may vary depending on other parameters.
  1957. In contrast to NumPy, Python's ``math.fsum`` function uses a slower but
  1958. more precise approach to summation.
  1959. Especially when summing a large number of lower precision floating point
  1960. numbers, such as ``float32``, numerical errors can become significant.
  1961. In such cases it can be advisable to use `dtype="float64"` to use a higher
  1962. precision for the output.
  1963. Examples
  1964. --------
  1965. >>> import numpy as np
  1966. >>> np.sum([0.5, 1.5])
  1967. 2.0
  1968. >>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32)
  1969. np.int32(1)
  1970. >>> np.sum([[0, 1], [0, 5]])
  1971. 6
  1972. >>> np.sum([[0, 1], [0, 5]], axis=0)
  1973. array([0, 6])
  1974. >>> np.sum([[0, 1], [0, 5]], axis=1)
  1975. array([1, 5])
  1976. >>> np.sum([[0, 1], [np.nan, 5]], where=[False, True], axis=1)
  1977. array([1., 5.])
  1978. If the accumulator is too small, overflow occurs:
  1979. >>> np.ones(128, dtype=np.int8).sum(dtype=np.int8)
  1980. np.int8(-128)
  1981. You can also start the sum with a value other than zero:
  1982. >>> np.sum([10], initial=5)
  1983. 15
  1984. """
  1985. if isinstance(a, _gentype):
  1986. # 2018-02-25, 1.15.0
  1987. raise TypeError(
  1988. "Calling np.sum(generator) is deprecated."
  1989. "Use np.sum(np.fromiter(generator)) or "
  1990. "the python sum builtin instead.",
  1991. )
  1992. return _wrapreduction(
  1993. a, np.add, 'sum', axis, dtype, out,
  1994. keepdims=keepdims, initial=initial, where=where
  1995. )
  1996. def _any_dispatcher(a, axis=None, out=None, keepdims=None, *,
  1997. where=np._NoValue):
  1998. return (a, where, out)
  1999. @array_function_dispatch(_any_dispatcher)
  2000. def any(a, axis=None, out=None, keepdims=np._NoValue, *, where=np._NoValue):
  2001. """
  2002. Test whether any array element along a given axis evaluates to True.
  2003. Returns single boolean if `axis` is ``None``
  2004. Parameters
  2005. ----------
  2006. a : array_like
  2007. Input array or object that can be converted to an array.
  2008. axis : None or int or tuple of ints, optional
  2009. Axis or axes along which a logical OR reduction is performed.
  2010. The default (``axis=None``) is to perform a logical OR over all
  2011. the dimensions of the input array. `axis` may be negative, in
  2012. which case it counts from the last to the first axis. If this
  2013. is a tuple of ints, a reduction is performed on multiple
  2014. axes, instead of a single axis or all the axes as before.
  2015. out : ndarray, optional
  2016. Alternate output array in which to place the result. It must have
  2017. the same shape as the expected output and its type is preserved
  2018. (e.g., if it is of type float, then it will remain so, returning
  2019. 1.0 for True and 0.0 for False, regardless of the type of `a`).
  2020. See :ref:`ufuncs-output-type` for more details.
  2021. keepdims : bool, optional
  2022. If this is set to True, the axes which are reduced are left
  2023. in the result as dimensions with size one. With this option,
  2024. the result will broadcast correctly against the input array.
  2025. If the default value is passed, then `keepdims` will not be
  2026. passed through to the `any` method of sub-classes of
  2027. `ndarray`, however any non-default value will be. If the
  2028. sub-class' method does not implement `keepdims` any
  2029. exceptions will be raised.
  2030. where : array_like of bool, optional
  2031. Elements to include in checking for any `True` values.
  2032. See `~numpy.ufunc.reduce` for details.
  2033. .. versionadded:: 1.20.0
  2034. Returns
  2035. -------
  2036. any : bool or ndarray
  2037. A new boolean or `ndarray` is returned unless `out` is specified,
  2038. in which case a reference to `out` is returned.
  2039. See Also
  2040. --------
  2041. ndarray.any : equivalent method
  2042. all : Test whether all elements along a given axis evaluate to True.
  2043. Notes
  2044. -----
  2045. Not a Number (NaN), positive infinity and negative infinity evaluate
  2046. to `True` because these are not equal to zero.
  2047. .. versionchanged:: 2.0
  2048. Before NumPy 2.0, ``any`` did not return booleans for object dtype
  2049. input arrays.
  2050. This behavior is still available via ``np.logical_or.reduce``.
  2051. Examples
  2052. --------
  2053. >>> import numpy as np
  2054. >>> np.any([[True, False], [True, True]])
  2055. True
  2056. >>> np.any([[True, False, True ],
  2057. ... [False, False, False]], axis=0)
  2058. array([ True, False, True])
  2059. >>> np.any([-1, 0, 5])
  2060. True
  2061. >>> np.any([[np.nan], [np.inf]], axis=1, keepdims=True)
  2062. array([[ True],
  2063. [ True]])
  2064. >>> np.any([[True, False], [False, False]], where=[[False], [True]])
  2065. False
  2066. >>> a = np.array([[1, 0, 0],
  2067. ... [0, 0, 1],
  2068. ... [0, 0, 0]])
  2069. >>> np.any(a, axis=0)
  2070. array([ True, False, True])
  2071. >>> np.any(a, axis=1)
  2072. array([ True, True, False])
  2073. >>> o=np.array(False)
  2074. >>> z=np.any([-1, 4, 5], out=o)
  2075. >>> z, o
  2076. (array(True), array(True))
  2077. >>> # Check now that z is a reference to o
  2078. >>> z is o
  2079. True
  2080. >>> id(z), id(o) # identity of z and o # doctest: +SKIP
  2081. (191614240, 191614240)
  2082. """
  2083. return _wrapreduction_any_all(a, np.logical_or, 'any', axis, out,
  2084. keepdims=keepdims, where=where)
  2085. def _all_dispatcher(a, axis=None, out=None, keepdims=None, *,
  2086. where=None):
  2087. return (a, where, out)
  2088. @array_function_dispatch(_all_dispatcher)
  2089. def all(a, axis=None, out=None, keepdims=np._NoValue, *, where=np._NoValue):
  2090. """
  2091. Test whether all array elements along a given axis evaluate to True.
  2092. Parameters
  2093. ----------
  2094. a : array_like
  2095. Input array or object that can be converted to an array.
  2096. axis : None or int or tuple of ints, optional
  2097. Axis or axes along which a logical AND reduction is performed.
  2098. The default (``axis=None``) is to perform a logical AND over all
  2099. the dimensions of the input array. `axis` may be negative, in
  2100. which case it counts from the last to the first axis. If this
  2101. is a tuple of ints, a reduction is performed on multiple
  2102. axes, instead of a single axis or all the axes as before.
  2103. out : ndarray, optional
  2104. Alternate output array in which to place the result.
  2105. It must have the same shape as the expected output and its
  2106. type is preserved (e.g., if ``dtype(out)`` is float, the result
  2107. will consist of 0.0's and 1.0's). See :ref:`ufuncs-output-type`
  2108. for more details.
  2109. keepdims : bool, optional
  2110. If this is set to True, the axes which are reduced are left
  2111. in the result as dimensions with size one. With this option,
  2112. the result will broadcast correctly against the input array.
  2113. If the default value is passed, then `keepdims` will not be
  2114. passed through to the `all` method of sub-classes of
  2115. `ndarray`, however any non-default value will be. If the
  2116. sub-class' method does not implement `keepdims` any
  2117. exceptions will be raised.
  2118. where : array_like of bool, optional
  2119. Elements to include in checking for all `True` values.
  2120. See `~numpy.ufunc.reduce` for details.
  2121. .. versionadded:: 1.20.0
  2122. Returns
  2123. -------
  2124. all : ndarray, bool
  2125. A new boolean or array is returned unless `out` is specified,
  2126. in which case a reference to `out` is returned.
  2127. See Also
  2128. --------
  2129. ndarray.all : equivalent method
  2130. any : Test whether any element along a given axis evaluates to True.
  2131. Notes
  2132. -----
  2133. Not a Number (NaN), positive infinity and negative infinity
  2134. evaluate to `True` because these are not equal to zero.
  2135. .. versionchanged:: 2.0
  2136. Before NumPy 2.0, ``all`` did not return booleans for object dtype
  2137. input arrays.
  2138. This behavior is still available via ``np.logical_and.reduce``.
  2139. Examples
  2140. --------
  2141. >>> import numpy as np
  2142. >>> np.all([[True,False],[True,True]])
  2143. False
  2144. >>> np.all([[True,False],[True,True]], axis=0)
  2145. array([ True, False])
  2146. >>> np.all([-1, 4, 5])
  2147. True
  2148. >>> np.all([1.0, np.nan])
  2149. True
  2150. >>> np.all([[True, True], [False, True]], where=[[True], [False]])
  2151. True
  2152. >>> o=np.array(False)
  2153. >>> z=np.all([-1, 4, 5], out=o)
  2154. >>> id(z), id(o), z
  2155. (28293632, 28293632, array(True)) # may vary
  2156. """
  2157. return _wrapreduction_any_all(a, np.logical_and, 'all', axis, out,
  2158. keepdims=keepdims, where=where)
  2159. def _cumulative_func(x, func, axis, dtype, out, include_initial):
  2160. x = np.atleast_1d(x)
  2161. x_ndim = x.ndim
  2162. if axis is None:
  2163. if x_ndim >= 2:
  2164. raise ValueError("For arrays which have more than one dimension "
  2165. "``axis`` argument is required.")
  2166. axis = 0
  2167. if out is not None and include_initial:
  2168. item = [slice(None)] * x_ndim
  2169. item[axis] = slice(1, None)
  2170. func.accumulate(x, axis=axis, dtype=dtype, out=out[tuple(item)])
  2171. item[axis] = 0
  2172. out[tuple(item)] = func.identity
  2173. return out
  2174. res = func.accumulate(x, axis=axis, dtype=dtype, out=out)
  2175. if include_initial:
  2176. initial_shape = list(x.shape)
  2177. initial_shape[axis] = 1
  2178. res = np.concat(
  2179. [np.full_like(res, func.identity, shape=initial_shape), res],
  2180. axis=axis,
  2181. )
  2182. return res
  2183. def _cumulative_prod_dispatcher(x, /, *, axis=None, dtype=None, out=None,
  2184. include_initial=None):
  2185. return (x, out)
  2186. @array_function_dispatch(_cumulative_prod_dispatcher)
  2187. def cumulative_prod(x, /, *, axis=None, dtype=None, out=None,
  2188. include_initial=False):
  2189. """
  2190. Return the cumulative product of elements along a given axis.
  2191. This function is an Array API compatible alternative to `numpy.cumprod`.
  2192. Parameters
  2193. ----------
  2194. x : array_like
  2195. Input array.
  2196. axis : int, optional
  2197. Axis along which the cumulative product is computed. The default
  2198. (None) is only allowed for one-dimensional arrays. For arrays
  2199. with more than one dimension ``axis`` is required.
  2200. dtype : dtype, optional
  2201. Type of the returned array, as well as of the accumulator in which
  2202. the elements are multiplied. If ``dtype`` is not specified, it
  2203. defaults to the dtype of ``x``, unless ``x`` has an integer dtype
  2204. with a precision less than that of the default platform integer.
  2205. In that case, the default platform integer is used instead.
  2206. out : ndarray, optional
  2207. Alternative output array in which to place the result. It must
  2208. have the same shape and buffer length as the expected output
  2209. but the type of the resulting values will be cast if necessary.
  2210. See :ref:`ufuncs-output-type` for more details.
  2211. include_initial : bool, optional
  2212. Boolean indicating whether to include the initial value (ones) as
  2213. the first value in the output. With ``include_initial=True``
  2214. the shape of the output is different than the shape of the input.
  2215. Default: ``False``.
  2216. Returns
  2217. -------
  2218. cumulative_prod_along_axis : ndarray
  2219. A new array holding the result is returned unless ``out`` is
  2220. specified, in which case a reference to ``out`` is returned. The
  2221. result has the same shape as ``x`` if ``include_initial=False``.
  2222. Notes
  2223. -----
  2224. Arithmetic is modular when using integer types, and no error is
  2225. raised on overflow.
  2226. Examples
  2227. --------
  2228. >>> a = np.array([1, 2, 3])
  2229. >>> np.cumulative_prod(a) # intermediate results 1, 1*2
  2230. ... # total product 1*2*3 = 6
  2231. array([1, 2, 6])
  2232. >>> a = np.array([1, 2, 3, 4, 5, 6])
  2233. >>> np.cumulative_prod(a, dtype=float) # specify type of output
  2234. array([ 1., 2., 6., 24., 120., 720.])
  2235. The cumulative product for each column (i.e., over the rows) of ``b``:
  2236. >>> b = np.array([[1, 2, 3], [4, 5, 6]])
  2237. >>> np.cumulative_prod(b, axis=0)
  2238. array([[ 1, 2, 3],
  2239. [ 4, 10, 18]])
  2240. The cumulative product for each row (i.e. over the columns) of ``b``:
  2241. >>> np.cumulative_prod(b, axis=1)
  2242. array([[ 1, 2, 6],
  2243. [ 4, 20, 120]])
  2244. """
  2245. return _cumulative_func(x, um.multiply, axis, dtype, out, include_initial)
  2246. def _cumulative_sum_dispatcher(x, /, *, axis=None, dtype=None, out=None,
  2247. include_initial=None):
  2248. return (x, out)
  2249. @array_function_dispatch(_cumulative_sum_dispatcher)
  2250. def cumulative_sum(x, /, *, axis=None, dtype=None, out=None,
  2251. include_initial=False):
  2252. """
  2253. Return the cumulative sum of the elements along a given axis.
  2254. This function is an Array API compatible alternative to `numpy.cumsum`.
  2255. Parameters
  2256. ----------
  2257. x : array_like
  2258. Input array.
  2259. axis : int, optional
  2260. Axis along which the cumulative sum is computed. The default
  2261. (None) is only allowed for one-dimensional arrays. For arrays
  2262. with more than one dimension ``axis`` is required.
  2263. dtype : dtype, optional
  2264. Type of the returned array and of the accumulator in which the
  2265. elements are summed. If ``dtype`` is not specified, it defaults
  2266. to the dtype of ``x``, unless ``x`` has an integer dtype with
  2267. a precision less than that of the default platform integer.
  2268. In that case, the default platform integer is used.
  2269. out : ndarray, optional
  2270. Alternative output array in which to place the result. It must
  2271. have the same shape and buffer length as the expected output
  2272. but the type will be cast if necessary. See :ref:`ufuncs-output-type`
  2273. for more details.
  2274. include_initial : bool, optional
  2275. Boolean indicating whether to include the initial value (zeros) as
  2276. the first value in the output. With ``include_initial=True``
  2277. the shape of the output is different than the shape of the input.
  2278. Default: ``False``.
  2279. Returns
  2280. -------
  2281. cumulative_sum_along_axis : ndarray
  2282. A new array holding the result is returned unless ``out`` is
  2283. specified, in which case a reference to ``out`` is returned. The
  2284. result has the same shape as ``x`` if ``include_initial=False``.
  2285. See Also
  2286. --------
  2287. sum : Sum array elements.
  2288. trapezoid : Integration of array values using composite trapezoidal rule.
  2289. diff : Calculate the n-th discrete difference along given axis.
  2290. Notes
  2291. -----
  2292. Arithmetic is modular when using integer types, and no error is
  2293. raised on overflow.
  2294. ``cumulative_sum(a)[-1]`` may not be equal to ``sum(a)`` for
  2295. floating-point values since ``sum`` may use a pairwise summation routine,
  2296. reducing the roundoff-error. See `sum` for more information.
  2297. Examples
  2298. --------
  2299. >>> a = np.array([1, 2, 3, 4, 5, 6])
  2300. >>> a
  2301. array([1, 2, 3, 4, 5, 6])
  2302. >>> np.cumulative_sum(a)
  2303. array([ 1, 3, 6, 10, 15, 21])
  2304. >>> np.cumulative_sum(a, dtype=float) # specifies type of output value(s)
  2305. array([ 1., 3., 6., 10., 15., 21.])
  2306. >>> b = np.array([[1, 2, 3], [4, 5, 6]])
  2307. >>> np.cumulative_sum(b,axis=0) # sum over rows for each of the 3 columns
  2308. array([[1, 2, 3],
  2309. [5, 7, 9]])
  2310. >>> np.cumulative_sum(b,axis=1) # sum over columns for each of the 2 rows
  2311. array([[ 1, 3, 6],
  2312. [ 4, 9, 15]])
  2313. ``cumulative_sum(c)[-1]`` may not be equal to ``sum(c)``
  2314. >>> c = np.array([1, 2e-9, 3e-9] * 1000000)
  2315. >>> np.cumulative_sum(c)[-1]
  2316. 1000000.0050045159
  2317. >>> c.sum()
  2318. 1000000.0050000029
  2319. """
  2320. return _cumulative_func(x, um.add, axis, dtype, out, include_initial)
  2321. def _cumsum_dispatcher(a, axis=None, dtype=None, out=None):
  2322. return (a, out)
  2323. @array_function_dispatch(_cumsum_dispatcher)
  2324. def cumsum(a, axis=None, dtype=None, out=None):
  2325. """
  2326. Return the cumulative sum of the elements along a given axis.
  2327. Parameters
  2328. ----------
  2329. a : array_like
  2330. Input array.
  2331. axis : int, optional
  2332. Axis along which the cumulative sum is computed. The default
  2333. (None) is to compute the cumsum over the flattened array.
  2334. dtype : dtype, optional
  2335. Type of the returned array and of the accumulator in which the
  2336. elements are summed. If `dtype` is not specified, it defaults
  2337. to the dtype of `a`, unless `a` has an integer dtype with a
  2338. precision less than that of the default platform integer. In
  2339. that case, the default platform integer is used.
  2340. out : ndarray, optional
  2341. Alternative output array in which to place the result. It must
  2342. have the same shape and buffer length as the expected output
  2343. but the type will be cast if necessary. See :ref:`ufuncs-output-type`
  2344. for more details.
  2345. Returns
  2346. -------
  2347. cumsum_along_axis : ndarray.
  2348. A new array holding the result is returned unless `out` is
  2349. specified, in which case a reference to `out` is returned. The
  2350. result has the same size as `a`, and the same shape as `a` if
  2351. `axis` is not None or `a` is a 1-d array.
  2352. See Also
  2353. --------
  2354. cumulative_sum : Array API compatible alternative for ``cumsum``.
  2355. sum : Sum array elements.
  2356. trapezoid : Integration of array values using composite trapezoidal rule.
  2357. diff : Calculate the n-th discrete difference along given axis.
  2358. Notes
  2359. -----
  2360. Arithmetic is modular when using integer types, and no error is
  2361. raised on overflow.
  2362. ``cumsum(a)[-1]`` may not be equal to ``sum(a)`` for floating-point
  2363. values since ``sum`` may use a pairwise summation routine, reducing
  2364. the roundoff-error. See `sum` for more information.
  2365. Examples
  2366. --------
  2367. >>> import numpy as np
  2368. >>> a = np.array([[1,2,3], [4,5,6]])
  2369. >>> a
  2370. array([[1, 2, 3],
  2371. [4, 5, 6]])
  2372. >>> np.cumsum(a)
  2373. array([ 1, 3, 6, 10, 15, 21])
  2374. >>> np.cumsum(a, dtype=float) # specifies type of output value(s)
  2375. array([ 1., 3., 6., 10., 15., 21.])
  2376. >>> np.cumsum(a,axis=0) # sum over rows for each of the 3 columns
  2377. array([[1, 2, 3],
  2378. [5, 7, 9]])
  2379. >>> np.cumsum(a,axis=1) # sum over columns for each of the 2 rows
  2380. array([[ 1, 3, 6],
  2381. [ 4, 9, 15]])
  2382. ``cumsum(b)[-1]`` may not be equal to ``sum(b)``
  2383. >>> b = np.array([1, 2e-9, 3e-9] * 1000000)
  2384. >>> b.cumsum()[-1]
  2385. 1000000.0050045159
  2386. >>> b.sum()
  2387. 1000000.0050000029
  2388. """
  2389. return _wrapfunc(a, 'cumsum', axis=axis, dtype=dtype, out=out)
  2390. def _ptp_dispatcher(a, axis=None, out=None, keepdims=None):
  2391. return (a, out)
  2392. @array_function_dispatch(_ptp_dispatcher)
  2393. def ptp(a, axis=None, out=None, keepdims=np._NoValue):
  2394. """
  2395. Range of values (maximum - minimum) along an axis.
  2396. The name of the function comes from the acronym for 'peak to peak'.
  2397. .. warning::
  2398. `ptp` preserves the data type of the array. This means the
  2399. return value for an input of signed integers with n bits
  2400. (e.g. `numpy.int8`, `numpy.int16`, etc) is also a signed integer
  2401. with n bits. In that case, peak-to-peak values greater than
  2402. ``2**(n-1)-1`` will be returned as negative values. An example
  2403. with a work-around is shown below.
  2404. Parameters
  2405. ----------
  2406. a : array_like
  2407. Input values.
  2408. axis : None or int or tuple of ints, optional
  2409. Axis along which to find the peaks. By default, flatten the
  2410. array. `axis` may be negative, in
  2411. which case it counts from the last to the first axis.
  2412. If this is a tuple of ints, a reduction is performed on multiple
  2413. axes, instead of a single axis or all the axes as before.
  2414. out : array_like
  2415. Alternative output array in which to place the result. It must
  2416. have the same shape and buffer length as the expected output,
  2417. but the type of the output values will be cast if necessary.
  2418. keepdims : bool, optional
  2419. If this is set to True, the axes which are reduced are left
  2420. in the result as dimensions with size one. With this option,
  2421. the result will broadcast correctly against the input array.
  2422. If the default value is passed, then `keepdims` will not be
  2423. passed through to the `ptp` method of sub-classes of
  2424. `ndarray`, however any non-default value will be. If the
  2425. sub-class' method does not implement `keepdims` any
  2426. exceptions will be raised.
  2427. Returns
  2428. -------
  2429. ptp : ndarray or scalar
  2430. The range of a given array - `scalar` if array is one-dimensional
  2431. or a new array holding the result along the given axis
  2432. Examples
  2433. --------
  2434. >>> import numpy as np
  2435. >>> x = np.array([[4, 9, 2, 10],
  2436. ... [6, 9, 7, 12]])
  2437. >>> np.ptp(x, axis=1)
  2438. array([8, 6])
  2439. >>> np.ptp(x, axis=0)
  2440. array([2, 0, 5, 2])
  2441. >>> np.ptp(x)
  2442. 10
  2443. This example shows that a negative value can be returned when
  2444. the input is an array of signed integers.
  2445. >>> y = np.array([[1, 127],
  2446. ... [0, 127],
  2447. ... [-1, 127],
  2448. ... [-2, 127]], dtype=np.int8)
  2449. >>> np.ptp(y, axis=1)
  2450. array([ 126, 127, -128, -127], dtype=int8)
  2451. A work-around is to use the `view()` method to view the result as
  2452. unsigned integers with the same bit width:
  2453. >>> np.ptp(y, axis=1).view(np.uint8)
  2454. array([126, 127, 128, 129], dtype=uint8)
  2455. """
  2456. kwargs = {}
  2457. if keepdims is not np._NoValue:
  2458. kwargs['keepdims'] = keepdims
  2459. return _methods._ptp(a, axis=axis, out=out, **kwargs)
  2460. def _max_dispatcher(a, axis=None, out=None, keepdims=None, initial=None,
  2461. where=None):
  2462. return (a, out)
  2463. @array_function_dispatch(_max_dispatcher)
  2464. @set_module('numpy')
  2465. def max(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
  2466. where=np._NoValue):
  2467. """
  2468. Return the maximum of an array or maximum along an axis.
  2469. Parameters
  2470. ----------
  2471. a : array_like
  2472. Input data.
  2473. axis : None or int or tuple of ints, optional
  2474. Axis or axes along which to operate. By default, flattened input is
  2475. used. If this is a tuple of ints, the maximum is selected over
  2476. multiple axes, instead of a single axis or all the axes as before.
  2477. out : ndarray, optional
  2478. Alternative output array in which to place the result. Must
  2479. be of the same shape and buffer length as the expected output.
  2480. See :ref:`ufuncs-output-type` for more details.
  2481. keepdims : bool, optional
  2482. If this is set to True, the axes which are reduced are left
  2483. in the result as dimensions with size one. With this option,
  2484. the result will broadcast correctly against the input array.
  2485. If the default value is passed, then `keepdims` will not be
  2486. passed through to the ``max`` method of sub-classes of
  2487. `ndarray`, however any non-default value will be. If the
  2488. sub-class' method does not implement `keepdims` any
  2489. exceptions will be raised.
  2490. initial : scalar, optional
  2491. The minimum value of an output element. Must be present to allow
  2492. computation on empty slice. See `~numpy.ufunc.reduce` for details.
  2493. where : array_like of bool, optional
  2494. Elements to compare for the maximum. See `~numpy.ufunc.reduce`
  2495. for details.
  2496. Returns
  2497. -------
  2498. max : ndarray or scalar
  2499. Maximum of `a`. If `axis` is None, the result is a scalar value.
  2500. If `axis` is an int, the result is an array of dimension
  2501. ``a.ndim - 1``. If `axis` is a tuple, the result is an array of
  2502. dimension ``a.ndim - len(axis)``.
  2503. See Also
  2504. --------
  2505. amin :
  2506. The minimum value of an array along a given axis, propagating any NaNs.
  2507. nanmax :
  2508. The maximum value of an array along a given axis, ignoring any NaNs.
  2509. maximum :
  2510. Element-wise maximum of two arrays, propagating any NaNs.
  2511. fmax :
  2512. Element-wise maximum of two arrays, ignoring any NaNs.
  2513. argmax :
  2514. Return the indices of the maximum values.
  2515. nanmin, minimum, fmin
  2516. Notes
  2517. -----
  2518. NaN values are propagated, that is if at least one item is NaN, the
  2519. corresponding max value will be NaN as well. To ignore NaN values
  2520. (MATLAB behavior), please use nanmax.
  2521. Don't use `~numpy.max` for element-wise comparison of 2 arrays; when
  2522. ``a.shape[0]`` is 2, ``maximum(a[0], a[1])`` is faster than
  2523. ``max(a, axis=0)``.
  2524. Examples
  2525. --------
  2526. >>> import numpy as np
  2527. >>> a = np.arange(4).reshape((2,2))
  2528. >>> a
  2529. array([[0, 1],
  2530. [2, 3]])
  2531. >>> np.max(a) # Maximum of the flattened array
  2532. 3
  2533. >>> np.max(a, axis=0) # Maxima along the first axis
  2534. array([2, 3])
  2535. >>> np.max(a, axis=1) # Maxima along the second axis
  2536. array([1, 3])
  2537. >>> np.max(a, where=[False, True], initial=-1, axis=0)
  2538. array([-1, 3])
  2539. >>> b = np.arange(5, dtype=float)
  2540. >>> b[2] = np.nan
  2541. >>> np.max(b)
  2542. np.float64(nan)
  2543. >>> np.max(b, where=~np.isnan(b), initial=-1)
  2544. 4.0
  2545. >>> np.nanmax(b)
  2546. 4.0
  2547. You can use an initial value to compute the maximum of an empty slice, or
  2548. to initialize it to a different value:
  2549. >>> np.max([[-50], [10]], axis=-1, initial=0)
  2550. array([ 0, 10])
  2551. Notice that the initial value is used as one of the elements for which the
  2552. maximum is determined, unlike for the default argument Python's max
  2553. function, which is only used for empty iterables.
  2554. >>> np.max([5], initial=6)
  2555. 6
  2556. >>> max([5], default=6)
  2557. 5
  2558. """
  2559. return _wrapreduction(a, np.maximum, 'max', axis, None, out,
  2560. keepdims=keepdims, initial=initial, where=where)
  2561. @array_function_dispatch(_max_dispatcher)
  2562. def amax(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
  2563. where=np._NoValue):
  2564. """
  2565. Return the maximum of an array or maximum along an axis.
  2566. `amax` is an alias of `~numpy.max`.
  2567. See Also
  2568. --------
  2569. max : alias of this function
  2570. ndarray.max : equivalent method
  2571. """
  2572. return _wrapreduction(a, np.maximum, 'max', axis, None, out,
  2573. keepdims=keepdims, initial=initial, where=where)
  2574. def _min_dispatcher(a, axis=None, out=None, keepdims=None, initial=None,
  2575. where=None):
  2576. return (a, out)
  2577. @array_function_dispatch(_min_dispatcher)
  2578. def min(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
  2579. where=np._NoValue):
  2580. """
  2581. Return the minimum of an array or minimum along an axis.
  2582. Parameters
  2583. ----------
  2584. a : array_like
  2585. Input data.
  2586. axis : None or int or tuple of ints, optional
  2587. Axis or axes along which to operate. By default, flattened input is
  2588. used.
  2589. If this is a tuple of ints, the minimum is selected over multiple axes,
  2590. instead of a single axis or all the axes as before.
  2591. out : ndarray, optional
  2592. Alternative output array in which to place the result. Must
  2593. be of the same shape and buffer length as the expected output.
  2594. See :ref:`ufuncs-output-type` for more details.
  2595. keepdims : bool, optional
  2596. If this is set to True, the axes which are reduced are left
  2597. in the result as dimensions with size one. With this option,
  2598. the result will broadcast correctly against the input array.
  2599. If the default value is passed, then `keepdims` will not be
  2600. passed through to the ``min`` method of sub-classes of
  2601. `ndarray`, however any non-default value will be. If the
  2602. sub-class' method does not implement `keepdims` any
  2603. exceptions will be raised.
  2604. initial : scalar, optional
  2605. The maximum value of an output element. Must be present to allow
  2606. computation on empty slice. See `~numpy.ufunc.reduce` for details.
  2607. where : array_like of bool, optional
  2608. Elements to compare for the minimum. See `~numpy.ufunc.reduce`
  2609. for details.
  2610. Returns
  2611. -------
  2612. min : ndarray or scalar
  2613. Minimum of `a`. If `axis` is None, the result is a scalar value.
  2614. If `axis` is an int, the result is an array of dimension
  2615. ``a.ndim - 1``. If `axis` is a tuple, the result is an array of
  2616. dimension ``a.ndim - len(axis)``.
  2617. See Also
  2618. --------
  2619. amax :
  2620. The maximum value of an array along a given axis, propagating any NaNs.
  2621. nanmin :
  2622. The minimum value of an array along a given axis, ignoring any NaNs.
  2623. minimum :
  2624. Element-wise minimum of two arrays, propagating any NaNs.
  2625. fmin :
  2626. Element-wise minimum of two arrays, ignoring any NaNs.
  2627. argmin :
  2628. Return the indices of the minimum values.
  2629. nanmax, maximum, fmax
  2630. Notes
  2631. -----
  2632. NaN values are propagated, that is if at least one item is NaN, the
  2633. corresponding min value will be NaN as well. To ignore NaN values
  2634. (MATLAB behavior), please use nanmin.
  2635. Don't use `~numpy.min` for element-wise comparison of 2 arrays; when
  2636. ``a.shape[0]`` is 2, ``minimum(a[0], a[1])`` is faster than
  2637. ``min(a, axis=0)``.
  2638. Examples
  2639. --------
  2640. >>> import numpy as np
  2641. >>> a = np.arange(4).reshape((2,2))
  2642. >>> a
  2643. array([[0, 1],
  2644. [2, 3]])
  2645. >>> np.min(a) # Minimum of the flattened array
  2646. 0
  2647. >>> np.min(a, axis=0) # Minima along the first axis
  2648. array([0, 1])
  2649. >>> np.min(a, axis=1) # Minima along the second axis
  2650. array([0, 2])
  2651. >>> np.min(a, where=[False, True], initial=10, axis=0)
  2652. array([10, 1])
  2653. >>> b = np.arange(5, dtype=float)
  2654. >>> b[2] = np.nan
  2655. >>> np.min(b)
  2656. np.float64(nan)
  2657. >>> np.min(b, where=~np.isnan(b), initial=10)
  2658. 0.0
  2659. >>> np.nanmin(b)
  2660. 0.0
  2661. >>> np.min([[-50], [10]], axis=-1, initial=0)
  2662. array([-50, 0])
  2663. Notice that the initial value is used as one of the elements for which the
  2664. minimum is determined, unlike for the default argument Python's max
  2665. function, which is only used for empty iterables.
  2666. Notice that this isn't the same as Python's ``default`` argument.
  2667. >>> np.min([6], initial=5)
  2668. 5
  2669. >>> min([6], default=5)
  2670. 6
  2671. """
  2672. return _wrapreduction(a, np.minimum, 'min', axis, None, out,
  2673. keepdims=keepdims, initial=initial, where=where)
  2674. @array_function_dispatch(_min_dispatcher)
  2675. def amin(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
  2676. where=np._NoValue):
  2677. """
  2678. Return the minimum of an array or minimum along an axis.
  2679. `amin` is an alias of `~numpy.min`.
  2680. See Also
  2681. --------
  2682. min : alias of this function
  2683. ndarray.min : equivalent method
  2684. """
  2685. return _wrapreduction(a, np.minimum, 'min', axis, None, out,
  2686. keepdims=keepdims, initial=initial, where=where)
  2687. def _prod_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None,
  2688. initial=None, where=None):
  2689. return (a, out)
  2690. @array_function_dispatch(_prod_dispatcher)
  2691. def prod(a, axis=None, dtype=None, out=None, keepdims=np._NoValue,
  2692. initial=np._NoValue, where=np._NoValue):
  2693. """
  2694. Return the product of array elements over a given axis.
  2695. Parameters
  2696. ----------
  2697. a : array_like
  2698. Input data.
  2699. axis : None or int or tuple of ints, optional
  2700. Axis or axes along which a product is performed. The default,
  2701. axis=None, will calculate the product of all the elements in the
  2702. input array. If axis is negative it counts from the last to the
  2703. first axis.
  2704. If axis is a tuple of ints, a product is performed on all of the
  2705. axes specified in the tuple instead of a single axis or all the
  2706. axes as before.
  2707. dtype : dtype, optional
  2708. The type of the returned array, as well as of the accumulator in
  2709. which the elements are multiplied. The dtype of `a` is used by
  2710. default unless `a` has an integer dtype of less precision than the
  2711. default platform integer. In that case, if `a` is signed then the
  2712. platform integer is used while if `a` is unsigned then an unsigned
  2713. integer of the same precision as the platform integer is used.
  2714. out : ndarray, optional
  2715. Alternative output array in which to place the result. It must have
  2716. the same shape as the expected output, but the type of the output
  2717. values will be cast if necessary.
  2718. keepdims : bool, optional
  2719. If this is set to True, the axes which are reduced are left in the
  2720. result as dimensions with size one. With this option, the result
  2721. will broadcast correctly against the input array.
  2722. If the default value is passed, then `keepdims` will not be
  2723. passed through to the `prod` method of sub-classes of
  2724. `ndarray`, however any non-default value will be. If the
  2725. sub-class' method does not implement `keepdims` any
  2726. exceptions will be raised.
  2727. initial : scalar, optional
  2728. The starting value for this product. See `~numpy.ufunc.reduce`
  2729. for details.
  2730. where : array_like of bool, optional
  2731. Elements to include in the product. See `~numpy.ufunc.reduce`
  2732. for details.
  2733. Returns
  2734. -------
  2735. product_along_axis : ndarray, see `dtype` parameter above.
  2736. An array shaped as `a` but with the specified axis removed.
  2737. Returns a reference to `out` if specified.
  2738. See Also
  2739. --------
  2740. ndarray.prod : equivalent method
  2741. :ref:`ufuncs-output-type`
  2742. Notes
  2743. -----
  2744. Arithmetic is modular when using integer types, and no error is
  2745. raised on overflow. That means that, on a 32-bit platform:
  2746. >>> x = np.array([536870910, 536870910, 536870910, 536870910])
  2747. >>> np.prod(x)
  2748. 16 # may vary
  2749. The product of an empty array is the neutral element 1:
  2750. >>> np.prod([])
  2751. 1.0
  2752. Examples
  2753. --------
  2754. By default, calculate the product of all elements:
  2755. >>> import numpy as np
  2756. >>> np.prod([1.,2.])
  2757. 2.0
  2758. Even when the input array is two-dimensional:
  2759. >>> a = np.array([[1., 2.], [3., 4.]])
  2760. >>> np.prod(a)
  2761. 24.0
  2762. But we can also specify the axis over which to multiply:
  2763. >>> np.prod(a, axis=1)
  2764. array([ 2., 12.])
  2765. >>> np.prod(a, axis=0)
  2766. array([3., 8.])
  2767. Or select specific elements to include:
  2768. >>> np.prod([1., np.nan, 3.], where=[True, False, True])
  2769. 3.0
  2770. If the type of `x` is unsigned, then the output type is
  2771. the unsigned platform integer:
  2772. >>> x = np.array([1, 2, 3], dtype=np.uint8)
  2773. >>> np.prod(x).dtype == np.uint
  2774. True
  2775. If `x` is of a signed integer type, then the output type
  2776. is the default platform integer:
  2777. >>> x = np.array([1, 2, 3], dtype=np.int8)
  2778. >>> np.prod(x).dtype == int
  2779. True
  2780. You can also start the product with a value other than one:
  2781. >>> np.prod([1, 2], initial=5)
  2782. 10
  2783. """
  2784. return _wrapreduction(a, np.multiply, 'prod', axis, dtype, out,
  2785. keepdims=keepdims, initial=initial, where=where)
  2786. def _cumprod_dispatcher(a, axis=None, dtype=None, out=None):
  2787. return (a, out)
  2788. @array_function_dispatch(_cumprod_dispatcher)
  2789. def cumprod(a, axis=None, dtype=None, out=None):
  2790. """
  2791. Return the cumulative product of elements along a given axis.
  2792. Parameters
  2793. ----------
  2794. a : array_like
  2795. Input array.
  2796. axis : int, optional
  2797. Axis along which the cumulative product is computed. By default
  2798. the input is flattened.
  2799. dtype : dtype, optional
  2800. Type of the returned array, as well as of the accumulator in which
  2801. the elements are multiplied. If *dtype* is not specified, it
  2802. defaults to the dtype of `a`, unless `a` has an integer dtype with
  2803. a precision less than that of the default platform integer. In
  2804. that case, the default platform integer is used instead.
  2805. out : ndarray, optional
  2806. Alternative output array in which to place the result. It must
  2807. have the same shape and buffer length as the expected output
  2808. but the type of the resulting values will be cast if necessary.
  2809. Returns
  2810. -------
  2811. cumprod : ndarray
  2812. A new array holding the result is returned unless `out` is
  2813. specified, in which case a reference to out is returned.
  2814. See Also
  2815. --------
  2816. cumulative_prod : Array API compatible alternative for ``cumprod``.
  2817. :ref:`ufuncs-output-type`
  2818. Notes
  2819. -----
  2820. Arithmetic is modular when using integer types, and no error is
  2821. raised on overflow.
  2822. Examples
  2823. --------
  2824. >>> import numpy as np
  2825. >>> a = np.array([1,2,3])
  2826. >>> np.cumprod(a) # intermediate results 1, 1*2
  2827. ... # total product 1*2*3 = 6
  2828. array([1, 2, 6])
  2829. >>> a = np.array([[1, 2, 3], [4, 5, 6]])
  2830. >>> np.cumprod(a, dtype=float) # specify type of output
  2831. array([ 1., 2., 6., 24., 120., 720.])
  2832. The cumulative product for each column (i.e., over the rows) of `a`:
  2833. >>> np.cumprod(a, axis=0)
  2834. array([[ 1, 2, 3],
  2835. [ 4, 10, 18]])
  2836. The cumulative product for each row (i.e. over the columns) of `a`:
  2837. >>> np.cumprod(a,axis=1)
  2838. array([[ 1, 2, 6],
  2839. [ 4, 20, 120]])
  2840. """
  2841. return _wrapfunc(a, 'cumprod', axis=axis, dtype=dtype, out=out)
  2842. def _ndim_dispatcher(a):
  2843. return (a,)
  2844. @array_function_dispatch(_ndim_dispatcher)
  2845. def ndim(a):
  2846. """
  2847. Return the number of dimensions of an array.
  2848. Parameters
  2849. ----------
  2850. a : array_like
  2851. Input array. If it is not already an ndarray, a conversion is
  2852. attempted.
  2853. Returns
  2854. -------
  2855. number_of_dimensions : int
  2856. The number of dimensions in `a`. Scalars are zero-dimensional.
  2857. See Also
  2858. --------
  2859. ndarray.ndim : equivalent method
  2860. shape : dimensions of array
  2861. ndarray.shape : dimensions of array
  2862. Examples
  2863. --------
  2864. >>> import numpy as np
  2865. >>> np.ndim([[1,2,3],[4,5,6]])
  2866. 2
  2867. >>> np.ndim(np.array([[1,2,3],[4,5,6]]))
  2868. 2
  2869. >>> np.ndim(1)
  2870. 0
  2871. """
  2872. try:
  2873. return a.ndim
  2874. except AttributeError:
  2875. return asarray(a).ndim
  2876. def _size_dispatcher(a, axis=None):
  2877. return (a,)
  2878. @array_function_dispatch(_size_dispatcher)
  2879. def size(a, axis=None):
  2880. """
  2881. Return the number of elements along a given axis.
  2882. Parameters
  2883. ----------
  2884. a : array_like
  2885. Input data.
  2886. axis : None or int or tuple of ints, optional
  2887. Axis or axes along which the elements are counted. By default, give
  2888. the total number of elements.
  2889. .. versionchanged:: 2.4
  2890. Extended to accept multiple axes.
  2891. Returns
  2892. -------
  2893. element_count : int
  2894. Number of elements along the specified axis.
  2895. See Also
  2896. --------
  2897. shape : dimensions of array
  2898. ndarray.shape : dimensions of array
  2899. ndarray.size : number of elements in array
  2900. Examples
  2901. --------
  2902. >>> import numpy as np
  2903. >>> a = np.array([[1,2,3],[4,5,6]])
  2904. >>> np.size(a)
  2905. 6
  2906. >>> np.size(a,axis=1)
  2907. 3
  2908. >>> np.size(a,axis=0)
  2909. 2
  2910. >>> np.size(a,axis=(0,1))
  2911. 6
  2912. """
  2913. if axis is None:
  2914. try:
  2915. return a.size
  2916. except AttributeError:
  2917. return asarray(a).size
  2918. else:
  2919. _shape = shape(a)
  2920. from .numeric import normalize_axis_tuple
  2921. axis = normalize_axis_tuple(axis, len(_shape), allow_duplicate=False)
  2922. return math.prod(_shape[ax] for ax in axis)
  2923. def _round_dispatcher(a, decimals=None, out=None):
  2924. return (a, out)
  2925. @array_function_dispatch(_round_dispatcher)
  2926. def round(a, decimals=0, out=None):
  2927. """
  2928. Evenly round to the given number of decimals.
  2929. Parameters
  2930. ----------
  2931. a : array_like
  2932. Input data.
  2933. decimals : int, optional
  2934. Number of decimal places to round to (default: 0). If
  2935. decimals is negative, it specifies the number of positions to
  2936. the left of the decimal point.
  2937. out : ndarray, optional
  2938. Alternative output array in which to place the result. It must have
  2939. the same shape as the expected output, but the type of the output
  2940. values will be cast if necessary. See :ref:`ufuncs-output-type`
  2941. for more details.
  2942. Returns
  2943. -------
  2944. rounded_array : ndarray
  2945. An array of the same type as `a`, containing the rounded values.
  2946. Unless `out` was specified, a new array is created. A reference to
  2947. the result is returned.
  2948. The real and imaginary parts of complex numbers are rounded
  2949. separately. The result of rounding a float is a float.
  2950. See Also
  2951. --------
  2952. ndarray.round : equivalent method
  2953. around : an alias for this function
  2954. ceil, fix, floor, rint, trunc
  2955. Notes
  2956. -----
  2957. For values exactly halfway between rounded decimal values, NumPy
  2958. rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0,
  2959. -0.5 and 0.5 round to 0.0, etc.
  2960. ``np.round`` uses a fast but sometimes inexact algorithm to round
  2961. floating-point datatypes. For positive `decimals` it is equivalent to
  2962. ``np.true_divide(np.rint(a * 10**decimals), 10**decimals)``, which has
  2963. error due to the inexact representation of decimal fractions in the IEEE
  2964. floating point standard [1]_ and errors introduced when scaling by powers
  2965. of ten. For instance, note the extra "1" in the following:
  2966. >>> np.round(56294995342131.5, 3)
  2967. 56294995342131.51
  2968. If your goal is to print such values with a fixed number of decimals, it is
  2969. preferable to use numpy's float printing routines to limit the number of
  2970. printed decimals:
  2971. >>> np.format_float_positional(56294995342131.5, precision=3)
  2972. '56294995342131.5'
  2973. The float printing routines use an accurate but much more computationally
  2974. demanding algorithm to compute the number of digits after the decimal
  2975. point.
  2976. Alternatively, Python's builtin `round` function uses a more accurate
  2977. but slower algorithm for 64-bit floating point values:
  2978. >>> round(56294995342131.5, 3)
  2979. 56294995342131.5
  2980. >>> np.round(16.055, 2), round(16.055, 2) # equals 16.0549999999999997
  2981. (16.06, 16.05)
  2982. References
  2983. ----------
  2984. .. [1] "Lecture Notes on the Status of IEEE 754", William Kahan,
  2985. https://people.eecs.berkeley.edu/~wkahan/ieee754status/IEEE754.PDF
  2986. Examples
  2987. --------
  2988. >>> import numpy as np
  2989. >>> np.round([0.37, 1.64])
  2990. array([0., 2.])
  2991. >>> np.round([0.37, 1.64], decimals=1)
  2992. array([0.4, 1.6])
  2993. >>> np.round([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value
  2994. array([0., 2., 2., 4., 4.])
  2995. >>> np.round([1,2,3,11], decimals=1) # ndarray of ints is returned
  2996. array([ 1, 2, 3, 11])
  2997. >>> np.round([1,2,3,11], decimals=-1)
  2998. array([ 0, 0, 0, 10])
  2999. """
  3000. return _wrapfunc(a, 'round', decimals=decimals, out=out)
  3001. @array_function_dispatch(_round_dispatcher)
  3002. def around(a, decimals=0, out=None):
  3003. """
  3004. Round an array to the given number of decimals.
  3005. `around` is an alias of `~numpy.round`.
  3006. See Also
  3007. --------
  3008. ndarray.round : equivalent method
  3009. round : alias for this function
  3010. ceil, fix, floor, rint, trunc
  3011. """
  3012. return _wrapfunc(a, 'round', decimals=decimals, out=out)
  3013. def _mean_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None, *,
  3014. where=None):
  3015. return (a, where, out)
  3016. @array_function_dispatch(_mean_dispatcher)
  3017. def mean(a, axis=None, dtype=None, out=None, keepdims=np._NoValue, *,
  3018. where=np._NoValue):
  3019. """
  3020. Compute the arithmetic mean along the specified axis.
  3021. Returns the average of the array elements. The average is taken over
  3022. the flattened array by default, otherwise over the specified axis.
  3023. `float64` intermediate and return values are used for integer inputs.
  3024. Parameters
  3025. ----------
  3026. a : array_like
  3027. Array containing numbers whose mean is desired. If `a` is not an
  3028. array, a conversion is attempted.
  3029. axis : None or int or tuple of ints, optional
  3030. Axis or axes along which the means are computed. The default is to
  3031. compute the mean of the flattened array.
  3032. If this is a tuple of ints, a mean is performed over multiple axes,
  3033. instead of a single axis or all the axes as before.
  3034. dtype : data-type, optional
  3035. Type to use in computing the mean. For integer inputs, the default
  3036. is `float64`; for floating point inputs, it is the same as the
  3037. input dtype.
  3038. out : ndarray, optional
  3039. Alternate output array in which to place the result. The default
  3040. is ``None``; if provided, it must have the same shape as the
  3041. expected output, but the type will be cast if necessary.
  3042. See :ref:`ufuncs-output-type` for more details.
  3043. See :ref:`ufuncs-output-type` for more details.
  3044. keepdims : bool, optional
  3045. If this is set to True, the axes which are reduced are left
  3046. in the result as dimensions with size one. With this option,
  3047. the result will broadcast correctly against the input array.
  3048. If the default value is passed, then `keepdims` will not be
  3049. passed through to the `mean` method of sub-classes of
  3050. `ndarray`, however any non-default value will be. If the
  3051. sub-class' method does not implement `keepdims` any
  3052. exceptions will be raised.
  3053. where : array_like of bool, optional
  3054. Elements to include in the mean. See `~numpy.ufunc.reduce` for details.
  3055. .. versionadded:: 1.20.0
  3056. Returns
  3057. -------
  3058. m : ndarray, see dtype parameter above
  3059. If `out=None`, returns a new array containing the mean values,
  3060. otherwise a reference to the output array is returned.
  3061. See Also
  3062. --------
  3063. average : Weighted average
  3064. std, var, nanmean, nanstd, nanvar
  3065. Notes
  3066. -----
  3067. The arithmetic mean is the sum of the elements along the axis divided
  3068. by the number of elements.
  3069. Note that for floating-point input, the mean is computed using the
  3070. same precision the input has. Depending on the input data, this can
  3071. cause the results to be inaccurate, especially for `float32` (see
  3072. example below). Specifying a higher-precision accumulator using the
  3073. `dtype` keyword can alleviate this issue.
  3074. By default, `float16` results are computed using `float32` intermediates
  3075. for extra precision.
  3076. Examples
  3077. --------
  3078. >>> import numpy as np
  3079. >>> a = np.array([[1, 2], [3, 4]])
  3080. >>> np.mean(a)
  3081. 2.5
  3082. >>> np.mean(a, axis=0)
  3083. array([2., 3.])
  3084. >>> np.mean(a, axis=1)
  3085. array([1.5, 3.5])
  3086. In single precision, `mean` can be inaccurate:
  3087. >>> a = np.zeros((2, 512*512), dtype=np.float32)
  3088. >>> a[0, :] = 1.0
  3089. >>> a[1, :] = 0.1
  3090. >>> np.mean(a)
  3091. np.float32(0.54999924)
  3092. Computing the mean in float64 is more accurate:
  3093. >>> np.mean(a, dtype=np.float64)
  3094. 0.55000000074505806 # may vary
  3095. Computing the mean in timedelta64 is available:
  3096. >>> b = np.array([1, 3], dtype="timedelta64[D]")
  3097. >>> np.mean(b)
  3098. np.timedelta64(2,'D')
  3099. Specifying a where argument:
  3100. >>> a = np.array([[5, 9, 13], [14, 10, 12], [11, 15, 19]])
  3101. >>> np.mean(a)
  3102. 12.0
  3103. >>> np.mean(a, where=[[True], [False], [False]])
  3104. 9.0
  3105. """
  3106. kwargs = {}
  3107. if keepdims is not np._NoValue:
  3108. kwargs['keepdims'] = keepdims
  3109. if where is not np._NoValue:
  3110. kwargs['where'] = where
  3111. if type(a) is not mu.ndarray:
  3112. try:
  3113. mean = a.mean
  3114. except AttributeError:
  3115. pass
  3116. else:
  3117. return mean(axis=axis, dtype=dtype, out=out, **kwargs)
  3118. return _methods._mean(a, axis=axis, dtype=dtype,
  3119. out=out, **kwargs)
  3120. def _std_dispatcher(a, axis=None, dtype=None, out=None, ddof=None,
  3121. keepdims=None, *, where=None, mean=None, correction=None):
  3122. return (a, where, out, mean)
  3123. @array_function_dispatch(_std_dispatcher)
  3124. def std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue, *,
  3125. where=np._NoValue, mean=np._NoValue, correction=np._NoValue):
  3126. r"""
  3127. Compute the standard deviation along the specified axis.
  3128. Returns the standard deviation, a measure of the spread of a distribution,
  3129. of the array elements. The standard deviation is computed for the
  3130. flattened array by default, otherwise over the specified axis.
  3131. Parameters
  3132. ----------
  3133. a : array_like
  3134. Calculate the standard deviation of these values.
  3135. axis : None or int or tuple of ints, optional
  3136. Axis or axes along which the standard deviation is computed. The
  3137. default is to compute the standard deviation of the flattened array.
  3138. If this is a tuple of ints, a standard deviation is performed over
  3139. multiple axes, instead of a single axis or all the axes as before.
  3140. dtype : dtype, optional
  3141. Type to use in computing the standard deviation. For arrays of
  3142. integer type the default is float64, for arrays of float types it is
  3143. the same as the array type.
  3144. out : ndarray, optional
  3145. Alternative output array in which to place the result. It must have
  3146. the same shape as the expected output but the type (of the calculated
  3147. values) will be cast if necessary.
  3148. See :ref:`ufuncs-output-type` for more details.
  3149. ddof : {int, float}, optional
  3150. Means Delta Degrees of Freedom. The divisor used in calculations
  3151. is ``N - ddof``, where ``N`` represents the number of elements.
  3152. By default `ddof` is zero. See Notes for details about use of `ddof`.
  3153. keepdims : bool, optional
  3154. If this is set to True, the axes which are reduced are left
  3155. in the result as dimensions with size one. With this option,
  3156. the result will broadcast correctly against the input array.
  3157. If the default value is passed, then `keepdims` will not be
  3158. passed through to the `std` method of sub-classes of
  3159. `ndarray`, however any non-default value will be. If the
  3160. sub-class' method does not implement `keepdims` any
  3161. exceptions will be raised.
  3162. where : array_like of bool, optional
  3163. Elements to include in the standard deviation.
  3164. See `~numpy.ufunc.reduce` for details.
  3165. .. versionadded:: 1.20.0
  3166. mean : array_like, optional
  3167. Provide the mean to prevent its recalculation. The mean should have
  3168. a shape as if it was calculated with ``keepdims=True``.
  3169. The axis for the calculation of the mean should be the same as used in
  3170. the call to this std function.
  3171. .. versionadded:: 2.0.0
  3172. correction : {int, float}, optional
  3173. Array API compatible name for the ``ddof`` parameter. Only one of them
  3174. can be provided at the same time.
  3175. .. versionadded:: 2.0.0
  3176. Returns
  3177. -------
  3178. standard_deviation : ndarray, see dtype parameter above.
  3179. If `out` is None, return a new array containing the standard deviation,
  3180. otherwise return a reference to the output array.
  3181. See Also
  3182. --------
  3183. var, mean, nanmean, nanstd, nanvar
  3184. :ref:`ufuncs-output-type`
  3185. Notes
  3186. -----
  3187. There are several common variants of the array standard deviation
  3188. calculation. Assuming the input `a` is a one-dimensional NumPy array
  3189. and ``mean`` is either provided as an argument or computed as
  3190. ``a.mean()``, NumPy computes the standard deviation of an array as::
  3191. N = len(a)
  3192. d2 = abs(a - mean)**2 # abs is for complex `a`
  3193. var = d2.sum() / (N - ddof) # note use of `ddof`
  3194. std = var**0.5
  3195. Different values of the argument `ddof` are useful in different
  3196. contexts. NumPy's default ``ddof=0`` corresponds with the expression:
  3197. .. math::
  3198. \sqrt{\frac{\sum_i{|a_i - \bar{a}|^2 }}{N}}
  3199. which is sometimes called the "population standard deviation" in the field
  3200. of statistics because it applies the definition of standard deviation to
  3201. `a` as if `a` were a complete population of possible observations.
  3202. Many other libraries define the standard deviation of an array
  3203. differently, e.g.:
  3204. .. math::
  3205. \sqrt{\frac{\sum_i{|a_i - \bar{a}|^2 }}{N - 1}}
  3206. In statistics, the resulting quantity is sometimes called the "sample
  3207. standard deviation" because if `a` is a random sample from a larger
  3208. population, this calculation provides the square root of an unbiased
  3209. estimate of the variance of the population. The use of :math:`N-1` in the
  3210. denominator is often called "Bessel's correction" because it corrects for
  3211. bias (toward lower values) in the variance estimate introduced when the
  3212. sample mean of `a` is used in place of the true mean of the population.
  3213. The resulting estimate of the standard deviation is still biased, but less
  3214. than it would have been without the correction. For this quantity, use
  3215. ``ddof=1``.
  3216. Note that, for complex numbers, `std` takes the absolute
  3217. value before squaring, so that the result is always real and nonnegative.
  3218. For floating-point input, the standard deviation is computed using the same
  3219. precision the input has. Depending on the input data, this can cause
  3220. the results to be inaccurate, especially for float32 (see example below).
  3221. Specifying a higher-accuracy accumulator using the `dtype` keyword can
  3222. alleviate this issue.
  3223. Examples
  3224. --------
  3225. >>> import numpy as np
  3226. >>> a = np.array([[1, 2], [3, 4]])
  3227. >>> np.std(a)
  3228. 1.1180339887498949 # may vary
  3229. >>> np.std(a, axis=0)
  3230. array([1., 1.])
  3231. >>> np.std(a, axis=1)
  3232. array([0.5, 0.5])
  3233. In single precision, std() can be inaccurate:
  3234. >>> a = np.zeros((2, 512*512), dtype=np.float32)
  3235. >>> a[0, :] = 1.0
  3236. >>> a[1, :] = 0.1
  3237. >>> np.std(a)
  3238. np.float32(0.45000005)
  3239. Computing the standard deviation in float64 is more accurate:
  3240. >>> np.std(a, dtype=np.float64)
  3241. 0.44999999925494177 # may vary
  3242. Specifying a where argument:
  3243. >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
  3244. >>> np.std(a)
  3245. 2.614064523559687 # may vary
  3246. >>> np.std(a, where=[[True], [True], [False]])
  3247. 2.0
  3248. Using the mean keyword to save computation time:
  3249. >>> import numpy as np
  3250. >>> from timeit import timeit
  3251. >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
  3252. >>> mean = np.mean(a, axis=1, keepdims=True)
  3253. >>>
  3254. >>> g = globals()
  3255. >>> n = 10000
  3256. >>> t1 = timeit("std = np.std(a, axis=1, mean=mean)", globals=g, number=n)
  3257. >>> t2 = timeit("std = np.std(a, axis=1)", globals=g, number=n)
  3258. >>> print(f'Percentage execution time saved {100*(t2-t1)/t2:.0f}%')
  3259. #doctest: +SKIP
  3260. Percentage execution time saved 30%
  3261. """
  3262. kwargs = {}
  3263. if keepdims is not np._NoValue:
  3264. kwargs['keepdims'] = keepdims
  3265. if where is not np._NoValue:
  3266. kwargs['where'] = where
  3267. if mean is not np._NoValue:
  3268. kwargs['mean'] = mean
  3269. if correction != np._NoValue:
  3270. if ddof != 0:
  3271. raise ValueError(
  3272. "ddof and correction can't be provided simultaneously."
  3273. )
  3274. else:
  3275. ddof = correction
  3276. if type(a) is not mu.ndarray:
  3277. try:
  3278. std = a.std
  3279. except AttributeError:
  3280. pass
  3281. else:
  3282. return std(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)
  3283. return _methods._std(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
  3284. **kwargs)
  3285. def _var_dispatcher(a, axis=None, dtype=None, out=None, ddof=None,
  3286. keepdims=None, *, where=None, mean=None, correction=None):
  3287. return (a, where, out, mean)
  3288. @array_function_dispatch(_var_dispatcher)
  3289. def var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue, *,
  3290. where=np._NoValue, mean=np._NoValue, correction=np._NoValue):
  3291. r"""
  3292. Compute the variance along the specified axis.
  3293. Returns the variance of the array elements, a measure of the spread of a
  3294. distribution. The variance is computed for the flattened array by
  3295. default, otherwise over the specified axis.
  3296. Parameters
  3297. ----------
  3298. a : array_like
  3299. Array containing numbers whose variance is desired. If `a` is not an
  3300. array, a conversion is attempted.
  3301. axis : None or int or tuple of ints, optional
  3302. Axis or axes along which the variance is computed. The default is to
  3303. compute the variance of the flattened array.
  3304. If this is a tuple of ints, a variance is performed over multiple axes,
  3305. instead of a single axis or all the axes as before.
  3306. dtype : data-type, optional
  3307. Type to use in computing the variance. For arrays of integer type
  3308. the default is `float64`; for arrays of float types it is the same as
  3309. the array type.
  3310. out : ndarray, optional
  3311. Alternate output array in which to place the result. It must have
  3312. the same shape as the expected output, but the type is cast if
  3313. necessary.
  3314. ddof : {int, float}, optional
  3315. "Delta Degrees of Freedom": the divisor used in the calculation is
  3316. ``N - ddof``, where ``N`` represents the number of elements. By
  3317. default `ddof` is zero. See notes for details about use of `ddof`.
  3318. keepdims : bool, optional
  3319. If this is set to True, the axes which are reduced are left
  3320. in the result as dimensions with size one. With this option,
  3321. the result will broadcast correctly against the input array.
  3322. If the default value is passed, then `keepdims` will not be
  3323. passed through to the `var` method of sub-classes of
  3324. `ndarray`, however any non-default value will be. If the
  3325. sub-class' method does not implement `keepdims` any
  3326. exceptions will be raised.
  3327. where : array_like of bool, optional
  3328. Elements to include in the variance. See `~numpy.ufunc.reduce` for
  3329. details.
  3330. .. versionadded:: 1.20.0
  3331. mean : array like, optional
  3332. Provide the mean to prevent its recalculation. The mean should have
  3333. a shape as if it was calculated with ``keepdims=True``.
  3334. The axis for the calculation of the mean should be the same as used in
  3335. the call to this var function.
  3336. .. versionadded:: 2.0.0
  3337. correction : {int, float}, optional
  3338. Array API compatible name for the ``ddof`` parameter. Only one of them
  3339. can be provided at the same time.
  3340. .. versionadded:: 2.0.0
  3341. Returns
  3342. -------
  3343. variance : ndarray, see dtype parameter above
  3344. If ``out=None``, returns a new array containing the variance;
  3345. otherwise, a reference to the output array is returned.
  3346. See Also
  3347. --------
  3348. std, mean, nanmean, nanstd, nanvar
  3349. :ref:`ufuncs-output-type`
  3350. Notes
  3351. -----
  3352. There are several common variants of the array variance calculation.
  3353. Assuming the input `a` is a one-dimensional NumPy array and ``mean`` is
  3354. either provided as an argument or computed as ``a.mean()``, NumPy
  3355. computes the variance of an array as::
  3356. N = len(a)
  3357. d2 = abs(a - mean)**2 # abs is for complex `a`
  3358. var = d2.sum() / (N - ddof) # note use of `ddof`
  3359. Different values of the argument `ddof` are useful in different
  3360. contexts. NumPy's default ``ddof=0`` corresponds with the expression:
  3361. .. math::
  3362. \frac{\sum_i{|a_i - \bar{a}|^2 }}{N}
  3363. which is sometimes called the "population variance" in the field of
  3364. statistics because it applies the definition of variance to `a` as if `a`
  3365. were a complete population of possible observations.
  3366. Many other libraries define the variance of an array differently, e.g.:
  3367. .. math::
  3368. \frac{\sum_i{|a_i - \bar{a}|^2}}{N - 1}
  3369. In statistics, the resulting quantity is sometimes called the "sample
  3370. variance" because if `a` is a random sample from a larger population,
  3371. this calculation provides an unbiased estimate of the variance of the
  3372. population. The use of :math:`N-1` in the denominator is often called
  3373. "Bessel's correction" because it corrects for bias (toward lower values)
  3374. in the variance estimate introduced when the sample mean of `a` is used
  3375. in place of the true mean of the population. For this quantity, use
  3376. ``ddof=1``.
  3377. Note that for complex numbers, the absolute value is taken before
  3378. squaring, so that the result is always real and nonnegative.
  3379. For floating-point input, the variance is computed using the same
  3380. precision the input has. Depending on the input data, this can cause
  3381. the results to be inaccurate, especially for `float32` (see example
  3382. below). Specifying a higher-accuracy accumulator using the ``dtype``
  3383. keyword can alleviate this issue.
  3384. Examples
  3385. --------
  3386. >>> import numpy as np
  3387. >>> a = np.array([[1, 2], [3, 4]])
  3388. >>> np.var(a)
  3389. 1.25
  3390. >>> np.var(a, axis=0)
  3391. array([1., 1.])
  3392. >>> np.var(a, axis=1)
  3393. array([0.25, 0.25])
  3394. In single precision, var() can be inaccurate:
  3395. >>> a = np.zeros((2, 512*512), dtype=np.float32)
  3396. >>> a[0, :] = 1.0
  3397. >>> a[1, :] = 0.1
  3398. >>> np.var(a)
  3399. np.float32(0.20250003)
  3400. Computing the variance in float64 is more accurate:
  3401. >>> np.var(a, dtype=np.float64)
  3402. 0.20249999932944759 # may vary
  3403. >>> ((1-0.55)**2 + (0.1-0.55)**2)/2
  3404. 0.2025
  3405. Specifying a where argument:
  3406. >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
  3407. >>> np.var(a)
  3408. 6.833333333333333 # may vary
  3409. >>> np.var(a, where=[[True], [True], [False]])
  3410. 4.0
  3411. Using the mean keyword to save computation time:
  3412. >>> import numpy as np
  3413. >>> from timeit import timeit
  3414. >>>
  3415. >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
  3416. >>> mean = np.mean(a, axis=1, keepdims=True)
  3417. >>>
  3418. >>> g = globals()
  3419. >>> n = 10000
  3420. >>> t1 = timeit("var = np.var(a, axis=1, mean=mean)", globals=g, number=n)
  3421. >>> t2 = timeit("var = np.var(a, axis=1)", globals=g, number=n)
  3422. >>> print(f'Percentage execution time saved {100*(t2-t1)/t2:.0f}%')
  3423. #doctest: +SKIP
  3424. Percentage execution time saved 32%
  3425. """
  3426. kwargs = {}
  3427. if keepdims is not np._NoValue:
  3428. kwargs['keepdims'] = keepdims
  3429. if where is not np._NoValue:
  3430. kwargs['where'] = where
  3431. if mean is not np._NoValue:
  3432. kwargs['mean'] = mean
  3433. if correction != np._NoValue:
  3434. if ddof != 0:
  3435. raise ValueError(
  3436. "ddof and correction can't be provided simultaneously."
  3437. )
  3438. else:
  3439. ddof = correction
  3440. if type(a) is not mu.ndarray:
  3441. try:
  3442. var = a.var
  3443. except AttributeError:
  3444. pass
  3445. else:
  3446. return var(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)
  3447. return _methods._var(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
  3448. **kwargs)