fromnumeric.py 126 KB

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