fromnumeric.py 107 KB

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