fromnumeric.py 116 KB

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