fromnumeric.py 119 KB

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