fromnumeric.py 122 KB

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