fromnumeric.py 115 KB

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