fromnumeric.py 141 KB

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