_add_newdocs.py 180 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284
  1. """
  2. This is only meant to add docs to objects defined in C-extension modules.
  3. The purpose is to allow easier editing of the docstrings without
  4. requiring a re-compile.
  5. NOTE: Many of the methods of ndarray have corresponding functions.
  6. If you update these docstrings, please keep also the ones in
  7. core/fromnumeric.py, core/defmatrix.py up-to-date.
  8. """
  9. from numpy.core.function_base import add_newdoc
  10. from numpy.core.overrides import array_function_like_doc
  11. ###############################################################################
  12. #
  13. # flatiter
  14. #
  15. # flatiter needs a toplevel description
  16. #
  17. ###############################################################################
  18. add_newdoc('numpy.core', 'flatiter',
  19. """
  20. Flat iterator object to iterate over arrays.
  21. A `flatiter` iterator is returned by ``x.flat`` for any array `x`.
  22. It allows iterating over the array as if it were a 1-D array,
  23. either in a for-loop or by calling its `next` method.
  24. Iteration is done in row-major, C-style order (the last
  25. index varying the fastest). The iterator can also be indexed using
  26. basic slicing or advanced indexing.
  27. See Also
  28. --------
  29. ndarray.flat : Return a flat iterator over an array.
  30. ndarray.flatten : Returns a flattened copy of an array.
  31. Notes
  32. -----
  33. A `flatiter` iterator can not be constructed directly from Python code
  34. by calling the `flatiter` constructor.
  35. Examples
  36. --------
  37. >>> x = np.arange(6).reshape(2, 3)
  38. >>> fl = x.flat
  39. >>> type(fl)
  40. <class 'numpy.flatiter'>
  41. >>> for item in fl:
  42. ... print(item)
  43. ...
  44. 0
  45. 1
  46. 2
  47. 3
  48. 4
  49. 5
  50. >>> fl[2:4]
  51. array([2, 3])
  52. """)
  53. # flatiter attributes
  54. add_newdoc('numpy.core', 'flatiter', ('base',
  55. """
  56. A reference to the array that is iterated over.
  57. Examples
  58. --------
  59. >>> x = np.arange(5)
  60. >>> fl = x.flat
  61. >>> fl.base is x
  62. True
  63. """))
  64. add_newdoc('numpy.core', 'flatiter', ('coords',
  65. """
  66. An N-dimensional tuple of current coordinates.
  67. Examples
  68. --------
  69. >>> x = np.arange(6).reshape(2, 3)
  70. >>> fl = x.flat
  71. >>> fl.coords
  72. (0, 0)
  73. >>> next(fl)
  74. 0
  75. >>> fl.coords
  76. (0, 1)
  77. """))
  78. add_newdoc('numpy.core', 'flatiter', ('index',
  79. """
  80. Current flat index into the array.
  81. Examples
  82. --------
  83. >>> x = np.arange(6).reshape(2, 3)
  84. >>> fl = x.flat
  85. >>> fl.index
  86. 0
  87. >>> next(fl)
  88. 0
  89. >>> fl.index
  90. 1
  91. """))
  92. # flatiter functions
  93. add_newdoc('numpy.core', 'flatiter', ('__array__',
  94. """__array__(type=None) Get array from iterator
  95. """))
  96. add_newdoc('numpy.core', 'flatiter', ('copy',
  97. """
  98. copy()
  99. Get a copy of the iterator as a 1-D array.
  100. Examples
  101. --------
  102. >>> x = np.arange(6).reshape(2, 3)
  103. >>> x
  104. array([[0, 1, 2],
  105. [3, 4, 5]])
  106. >>> fl = x.flat
  107. >>> fl.copy()
  108. array([0, 1, 2, 3, 4, 5])
  109. """))
  110. ###############################################################################
  111. #
  112. # nditer
  113. #
  114. ###############################################################################
  115. add_newdoc('numpy.core', 'nditer',
  116. """
  117. nditer(op, flags=None, op_flags=None, op_dtypes=None, order='K', casting='safe', op_axes=None, itershape=None, buffersize=0)
  118. Efficient multi-dimensional iterator object to iterate over arrays.
  119. To get started using this object, see the
  120. :ref:`introductory guide to array iteration <arrays.nditer>`.
  121. Parameters
  122. ----------
  123. op : ndarray or sequence of array_like
  124. The array(s) to iterate over.
  125. flags : sequence of str, optional
  126. Flags to control the behavior of the iterator.
  127. * ``buffered`` enables buffering when required.
  128. * ``c_index`` causes a C-order index to be tracked.
  129. * ``f_index`` causes a Fortran-order index to be tracked.
  130. * ``multi_index`` causes a multi-index, or a tuple of indices
  131. with one per iteration dimension, to be tracked.
  132. * ``common_dtype`` causes all the operands to be converted to
  133. a common data type, with copying or buffering as necessary.
  134. * ``copy_if_overlap`` causes the iterator to determine if read
  135. operands have overlap with write operands, and make temporary
  136. copies as necessary to avoid overlap. False positives (needless
  137. copying) are possible in some cases.
  138. * ``delay_bufalloc`` delays allocation of the buffers until
  139. a reset() call is made. Allows ``allocate`` operands to
  140. be initialized before their values are copied into the buffers.
  141. * ``external_loop`` causes the ``values`` given to be
  142. one-dimensional arrays with multiple values instead of
  143. zero-dimensional arrays.
  144. * ``grow_inner`` allows the ``value`` array sizes to be made
  145. larger than the buffer size when both ``buffered`` and
  146. ``external_loop`` is used.
  147. * ``ranged`` allows the iterator to be restricted to a sub-range
  148. of the iterindex values.
  149. * ``refs_ok`` enables iteration of reference types, such as
  150. object arrays.
  151. * ``reduce_ok`` enables iteration of ``readwrite`` operands
  152. which are broadcasted, also known as reduction operands.
  153. * ``zerosize_ok`` allows `itersize` to be zero.
  154. op_flags : list of list of str, optional
  155. This is a list of flags for each operand. At minimum, one of
  156. ``readonly``, ``readwrite``, or ``writeonly`` must be specified.
  157. * ``readonly`` indicates the operand will only be read from.
  158. * ``readwrite`` indicates the operand will be read from and written to.
  159. * ``writeonly`` indicates the operand will only be written to.
  160. * ``no_broadcast`` prevents the operand from being broadcasted.
  161. * ``contig`` forces the operand data to be contiguous.
  162. * ``aligned`` forces the operand data to be aligned.
  163. * ``nbo`` forces the operand data to be in native byte order.
  164. * ``copy`` allows a temporary read-only copy if required.
  165. * ``updateifcopy`` allows a temporary read-write copy if required.
  166. * ``allocate`` causes the array to be allocated if it is None
  167. in the ``op`` parameter.
  168. * ``no_subtype`` prevents an ``allocate`` operand from using a subtype.
  169. * ``arraymask`` indicates that this operand is the mask to use
  170. for selecting elements when writing to operands with the
  171. 'writemasked' flag set. The iterator does not enforce this,
  172. but when writing from a buffer back to the array, it only
  173. copies those elements indicated by this mask.
  174. * ``writemasked`` indicates that only elements where the chosen
  175. ``arraymask`` operand is True will be written to.
  176. * ``overlap_assume_elementwise`` can be used to mark operands that are
  177. accessed only in the iterator order, to allow less conservative
  178. copying when ``copy_if_overlap`` is present.
  179. op_dtypes : dtype or tuple of dtype(s), optional
  180. The required data type(s) of the operands. If copying or buffering
  181. is enabled, the data will be converted to/from their original types.
  182. order : {'C', 'F', 'A', 'K'}, optional
  183. Controls the iteration order. 'C' means C order, 'F' means
  184. Fortran order, 'A' means 'F' order if all the arrays are Fortran
  185. contiguous, 'C' order otherwise, and 'K' means as close to the
  186. order the array elements appear in memory as possible. This also
  187. affects the element memory order of ``allocate`` operands, as they
  188. are allocated to be compatible with iteration order.
  189. Default is 'K'.
  190. casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
  191. Controls what kind of data casting may occur when making a copy
  192. or buffering. Setting this to 'unsafe' is not recommended,
  193. as it can adversely affect accumulations.
  194. * 'no' means the data types should not be cast at all.
  195. * 'equiv' means only byte-order changes are allowed.
  196. * 'safe' means only casts which can preserve values are allowed.
  197. * 'same_kind' means only safe casts or casts within a kind,
  198. like float64 to float32, are allowed.
  199. * 'unsafe' means any data conversions may be done.
  200. op_axes : list of list of ints, optional
  201. If provided, is a list of ints or None for each operands.
  202. The list of axes for an operand is a mapping from the dimensions
  203. of the iterator to the dimensions of the operand. A value of
  204. -1 can be placed for entries, causing that dimension to be
  205. treated as `newaxis`.
  206. itershape : tuple of ints, optional
  207. The desired shape of the iterator. This allows ``allocate`` operands
  208. with a dimension mapped by op_axes not corresponding to a dimension
  209. of a different operand to get a value not equal to 1 for that
  210. dimension.
  211. buffersize : int, optional
  212. When buffering is enabled, controls the size of the temporary
  213. buffers. Set to 0 for the default value.
  214. Attributes
  215. ----------
  216. dtypes : tuple of dtype(s)
  217. The data types of the values provided in `value`. This may be
  218. different from the operand data types if buffering is enabled.
  219. Valid only before the iterator is closed.
  220. finished : bool
  221. Whether the iteration over the operands is finished or not.
  222. has_delayed_bufalloc : bool
  223. If True, the iterator was created with the ``delay_bufalloc`` flag,
  224. and no reset() function was called on it yet.
  225. has_index : bool
  226. If True, the iterator was created with either the ``c_index`` or
  227. the ``f_index`` flag, and the property `index` can be used to
  228. retrieve it.
  229. has_multi_index : bool
  230. If True, the iterator was created with the ``multi_index`` flag,
  231. and the property `multi_index` can be used to retrieve it.
  232. index
  233. When the ``c_index`` or ``f_index`` flag was used, this property
  234. provides access to the index. Raises a ValueError if accessed
  235. and ``has_index`` is False.
  236. iterationneedsapi : bool
  237. Whether iteration requires access to the Python API, for example
  238. if one of the operands is an object array.
  239. iterindex : int
  240. An index which matches the order of iteration.
  241. itersize : int
  242. Size of the iterator.
  243. itviews
  244. Structured view(s) of `operands` in memory, matching the reordered
  245. and optimized iterator access pattern. Valid only before the iterator
  246. is closed.
  247. multi_index
  248. When the ``multi_index`` flag was used, this property
  249. provides access to the index. Raises a ValueError if accessed
  250. accessed and ``has_multi_index`` is False.
  251. ndim : int
  252. The dimensions of the iterator.
  253. nop : int
  254. The number of iterator operands.
  255. operands : tuple of operand(s)
  256. The array(s) to be iterated over. Valid only before the iterator is
  257. closed.
  258. shape : tuple of ints
  259. Shape tuple, the shape of the iterator.
  260. value
  261. Value of ``operands`` at current iteration. Normally, this is a
  262. tuple of array scalars, but if the flag ``external_loop`` is used,
  263. it is a tuple of one dimensional arrays.
  264. Notes
  265. -----
  266. `nditer` supersedes `flatiter`. The iterator implementation behind
  267. `nditer` is also exposed by the NumPy C API.
  268. The Python exposure supplies two iteration interfaces, one which follows
  269. the Python iterator protocol, and another which mirrors the C-style
  270. do-while pattern. The native Python approach is better in most cases, but
  271. if you need the coordinates or index of an iterator, use the C-style pattern.
  272. Examples
  273. --------
  274. Here is how we might write an ``iter_add`` function, using the
  275. Python iterator protocol:
  276. >>> def iter_add_py(x, y, out=None):
  277. ... addop = np.add
  278. ... it = np.nditer([x, y, out], [],
  279. ... [['readonly'], ['readonly'], ['writeonly','allocate']])
  280. ... with it:
  281. ... for (a, b, c) in it:
  282. ... addop(a, b, out=c)
  283. ... return it.operands[2]
  284. Here is the same function, but following the C-style pattern:
  285. >>> def iter_add(x, y, out=None):
  286. ... addop = np.add
  287. ... it = np.nditer([x, y, out], [],
  288. ... [['readonly'], ['readonly'], ['writeonly','allocate']])
  289. ... with it:
  290. ... while not it.finished:
  291. ... addop(it[0], it[1], out=it[2])
  292. ... it.iternext()
  293. ... return it.operands[2]
  294. Here is an example outer product function:
  295. >>> def outer_it(x, y, out=None):
  296. ... mulop = np.multiply
  297. ... it = np.nditer([x, y, out], ['external_loop'],
  298. ... [['readonly'], ['readonly'], ['writeonly', 'allocate']],
  299. ... op_axes=[list(range(x.ndim)) + [-1] * y.ndim,
  300. ... [-1] * x.ndim + list(range(y.ndim)),
  301. ... None])
  302. ... with it:
  303. ... for (a, b, c) in it:
  304. ... mulop(a, b, out=c)
  305. ... return it.operands[2]
  306. >>> a = np.arange(2)+1
  307. >>> b = np.arange(3)+1
  308. >>> outer_it(a,b)
  309. array([[1, 2, 3],
  310. [2, 4, 6]])
  311. Here is an example function which operates like a "lambda" ufunc:
  312. >>> def luf(lamdaexpr, *args, **kwargs):
  313. ... '''luf(lambdaexpr, op1, ..., opn, out=None, order='K', casting='safe', buffersize=0)'''
  314. ... nargs = len(args)
  315. ... op = (kwargs.get('out',None),) + args
  316. ... it = np.nditer(op, ['buffered','external_loop'],
  317. ... [['writeonly','allocate','no_broadcast']] +
  318. ... [['readonly','nbo','aligned']]*nargs,
  319. ... order=kwargs.get('order','K'),
  320. ... casting=kwargs.get('casting','safe'),
  321. ... buffersize=kwargs.get('buffersize',0))
  322. ... while not it.finished:
  323. ... it[0] = lamdaexpr(*it[1:])
  324. ... it.iternext()
  325. ... return it.operands[0]
  326. >>> a = np.arange(5)
  327. >>> b = np.ones(5)
  328. >>> luf(lambda i,j:i*i + j/2, a, b)
  329. array([ 0.5, 1.5, 4.5, 9.5, 16.5])
  330. If operand flags `"writeonly"` or `"readwrite"` are used the
  331. operands may be views into the original data with the
  332. `WRITEBACKIFCOPY` flag. In this case `nditer` must be used as a
  333. context manager or the `nditer.close` method must be called before
  334. using the result. The temporary data will be written back to the
  335. original data when the `__exit__` function is called but not before:
  336. >>> a = np.arange(6, dtype='i4')[::-2]
  337. >>> with np.nditer(a, [],
  338. ... [['writeonly', 'updateifcopy']],
  339. ... casting='unsafe',
  340. ... op_dtypes=[np.dtype('f4')]) as i:
  341. ... x = i.operands[0]
  342. ... x[:] = [-1, -2, -3]
  343. ... # a still unchanged here
  344. >>> a, x
  345. (array([-1, -2, -3], dtype=int32), array([-1., -2., -3.], dtype=float32))
  346. It is important to note that once the iterator is exited, dangling
  347. references (like `x` in the example) may or may not share data with
  348. the original data `a`. If writeback semantics were active, i.e. if
  349. `x.base.flags.writebackifcopy` is `True`, then exiting the iterator
  350. will sever the connection between `x` and `a`, writing to `x` will
  351. no longer write to `a`. If writeback semantics are not active, then
  352. `x.data` will still point at some part of `a.data`, and writing to
  353. one will affect the other.
  354. Context management and the `close` method appeared in version 1.15.0.
  355. """)
  356. # nditer methods
  357. add_newdoc('numpy.core', 'nditer', ('copy',
  358. """
  359. copy()
  360. Get a copy of the iterator in its current state.
  361. Examples
  362. --------
  363. >>> x = np.arange(10)
  364. >>> y = x + 1
  365. >>> it = np.nditer([x, y])
  366. >>> next(it)
  367. (array(0), array(1))
  368. >>> it2 = it.copy()
  369. >>> next(it2)
  370. (array(1), array(2))
  371. """))
  372. add_newdoc('numpy.core', 'nditer', ('operands',
  373. """
  374. operands[`Slice`]
  375. The array(s) to be iterated over. Valid only before the iterator is closed.
  376. """))
  377. add_newdoc('numpy.core', 'nditer', ('debug_print',
  378. """
  379. debug_print()
  380. Print the current state of the `nditer` instance and debug info to stdout.
  381. """))
  382. add_newdoc('numpy.core', 'nditer', ('enable_external_loop',
  383. """
  384. enable_external_loop()
  385. When the "external_loop" was not used during construction, but
  386. is desired, this modifies the iterator to behave as if the flag
  387. was specified.
  388. """))
  389. add_newdoc('numpy.core', 'nditer', ('iternext',
  390. """
  391. iternext()
  392. Check whether iterations are left, and perform a single internal iteration
  393. without returning the result. Used in the C-style pattern do-while
  394. pattern. For an example, see `nditer`.
  395. Returns
  396. -------
  397. iternext : bool
  398. Whether or not there are iterations left.
  399. """))
  400. add_newdoc('numpy.core', 'nditer', ('remove_axis',
  401. """
  402. remove_axis(i)
  403. Removes axis `i` from the iterator. Requires that the flag "multi_index"
  404. be enabled.
  405. """))
  406. add_newdoc('numpy.core', 'nditer', ('remove_multi_index',
  407. """
  408. remove_multi_index()
  409. When the "multi_index" flag was specified, this removes it, allowing
  410. the internal iteration structure to be optimized further.
  411. """))
  412. add_newdoc('numpy.core', 'nditer', ('reset',
  413. """
  414. reset()
  415. Reset the iterator to its initial state.
  416. """))
  417. add_newdoc('numpy.core', 'nested_iters',
  418. """
  419. Create nditers for use in nested loops
  420. Create a tuple of `nditer` objects which iterate in nested loops over
  421. different axes of the op argument. The first iterator is used in the
  422. outermost loop, the last in the innermost loop. Advancing one will change
  423. the subsequent iterators to point at its new element.
  424. Parameters
  425. ----------
  426. op : ndarray or sequence of array_like
  427. The array(s) to iterate over.
  428. axes : list of list of int
  429. Each item is used as an "op_axes" argument to an nditer
  430. flags, op_flags, op_dtypes, order, casting, buffersize (optional)
  431. See `nditer` parameters of the same name
  432. Returns
  433. -------
  434. iters : tuple of nditer
  435. An nditer for each item in `axes`, outermost first
  436. See Also
  437. --------
  438. nditer
  439. Examples
  440. --------
  441. Basic usage. Note how y is the "flattened" version of
  442. [a[:, 0, :], a[:, 1, 0], a[:, 2, :]] since we specified
  443. the first iter's axes as [1]
  444. >>> a = np.arange(12).reshape(2, 3, 2)
  445. >>> i, j = np.nested_iters(a, [[1], [0, 2]], flags=["multi_index"])
  446. >>> for x in i:
  447. ... print(i.multi_index)
  448. ... for y in j:
  449. ... print('', j.multi_index, y)
  450. (0,)
  451. (0, 0) 0
  452. (0, 1) 1
  453. (1, 0) 6
  454. (1, 1) 7
  455. (1,)
  456. (0, 0) 2
  457. (0, 1) 3
  458. (1, 0) 8
  459. (1, 1) 9
  460. (2,)
  461. (0, 0) 4
  462. (0, 1) 5
  463. (1, 0) 10
  464. (1, 1) 11
  465. """)
  466. add_newdoc('numpy.core', 'nditer', ('close',
  467. """
  468. close()
  469. Resolve all writeback semantics in writeable operands.
  470. .. versionadded:: 1.15.0
  471. See Also
  472. --------
  473. :ref:`nditer-context-manager`
  474. """))
  475. ###############################################################################
  476. #
  477. # broadcast
  478. #
  479. ###############################################################################
  480. add_newdoc('numpy.core', 'broadcast',
  481. """
  482. Produce an object that mimics broadcasting.
  483. Parameters
  484. ----------
  485. in1, in2, ... : array_like
  486. Input parameters.
  487. Returns
  488. -------
  489. b : broadcast object
  490. Broadcast the input parameters against one another, and
  491. return an object that encapsulates the result.
  492. Amongst others, it has ``shape`` and ``nd`` properties, and
  493. may be used as an iterator.
  494. See Also
  495. --------
  496. broadcast_arrays
  497. broadcast_to
  498. broadcast_shapes
  499. Examples
  500. --------
  501. Manually adding two vectors, using broadcasting:
  502. >>> x = np.array([[1], [2], [3]])
  503. >>> y = np.array([4, 5, 6])
  504. >>> b = np.broadcast(x, y)
  505. >>> out = np.empty(b.shape)
  506. >>> out.flat = [u+v for (u,v) in b]
  507. >>> out
  508. array([[5., 6., 7.],
  509. [6., 7., 8.],
  510. [7., 8., 9.]])
  511. Compare against built-in broadcasting:
  512. >>> x + y
  513. array([[5, 6, 7],
  514. [6, 7, 8],
  515. [7, 8, 9]])
  516. """)
  517. # attributes
  518. add_newdoc('numpy.core', 'broadcast', ('index',
  519. """
  520. current index in broadcasted result
  521. Examples
  522. --------
  523. >>> x = np.array([[1], [2], [3]])
  524. >>> y = np.array([4, 5, 6])
  525. >>> b = np.broadcast(x, y)
  526. >>> b.index
  527. 0
  528. >>> next(b), next(b), next(b)
  529. ((1, 4), (1, 5), (1, 6))
  530. >>> b.index
  531. 3
  532. """))
  533. add_newdoc('numpy.core', 'broadcast', ('iters',
  534. """
  535. tuple of iterators along ``self``'s "components."
  536. Returns a tuple of `numpy.flatiter` objects, one for each "component"
  537. of ``self``.
  538. See Also
  539. --------
  540. numpy.flatiter
  541. Examples
  542. --------
  543. >>> x = np.array([1, 2, 3])
  544. >>> y = np.array([[4], [5], [6]])
  545. >>> b = np.broadcast(x, y)
  546. >>> row, col = b.iters
  547. >>> next(row), next(col)
  548. (1, 4)
  549. """))
  550. add_newdoc('numpy.core', 'broadcast', ('ndim',
  551. """
  552. Number of dimensions of broadcasted result. Alias for `nd`.
  553. .. versionadded:: 1.12.0
  554. Examples
  555. --------
  556. >>> x = np.array([1, 2, 3])
  557. >>> y = np.array([[4], [5], [6]])
  558. >>> b = np.broadcast(x, y)
  559. >>> b.ndim
  560. 2
  561. """))
  562. add_newdoc('numpy.core', 'broadcast', ('nd',
  563. """
  564. Number of dimensions of broadcasted result. For code intended for NumPy
  565. 1.12.0 and later the more consistent `ndim` is preferred.
  566. Examples
  567. --------
  568. >>> x = np.array([1, 2, 3])
  569. >>> y = np.array([[4], [5], [6]])
  570. >>> b = np.broadcast(x, y)
  571. >>> b.nd
  572. 2
  573. """))
  574. add_newdoc('numpy.core', 'broadcast', ('numiter',
  575. """
  576. Number of iterators possessed by the broadcasted result.
  577. Examples
  578. --------
  579. >>> x = np.array([1, 2, 3])
  580. >>> y = np.array([[4], [5], [6]])
  581. >>> b = np.broadcast(x, y)
  582. >>> b.numiter
  583. 2
  584. """))
  585. add_newdoc('numpy.core', 'broadcast', ('shape',
  586. """
  587. Shape of broadcasted result.
  588. Examples
  589. --------
  590. >>> x = np.array([1, 2, 3])
  591. >>> y = np.array([[4], [5], [6]])
  592. >>> b = np.broadcast(x, y)
  593. >>> b.shape
  594. (3, 3)
  595. """))
  596. add_newdoc('numpy.core', 'broadcast', ('size',
  597. """
  598. Total size of broadcasted result.
  599. Examples
  600. --------
  601. >>> x = np.array([1, 2, 3])
  602. >>> y = np.array([[4], [5], [6]])
  603. >>> b = np.broadcast(x, y)
  604. >>> b.size
  605. 9
  606. """))
  607. add_newdoc('numpy.core', 'broadcast', ('reset',
  608. """
  609. reset()
  610. Reset the broadcasted result's iterator(s).
  611. Parameters
  612. ----------
  613. None
  614. Returns
  615. -------
  616. None
  617. Examples
  618. --------
  619. >>> x = np.array([1, 2, 3])
  620. >>> y = np.array([[4], [5], [6]])
  621. >>> b = np.broadcast(x, y)
  622. >>> b.index
  623. 0
  624. >>> next(b), next(b), next(b)
  625. ((1, 4), (2, 4), (3, 4))
  626. >>> b.index
  627. 3
  628. >>> b.reset()
  629. >>> b.index
  630. 0
  631. """))
  632. ###############################################################################
  633. #
  634. # numpy functions
  635. #
  636. ###############################################################################
  637. add_newdoc('numpy.core.multiarray', 'array',
  638. """
  639. array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0,
  640. like=None)
  641. Create an array.
  642. Parameters
  643. ----------
  644. object : array_like
  645. An array, any object exposing the array interface, an object whose
  646. __array__ method returns an array, or any (nested) sequence.
  647. dtype : data-type, optional
  648. The desired data-type for the array. If not given, then the type will
  649. be determined as the minimum type required to hold the objects in the
  650. sequence.
  651. copy : bool, optional
  652. If true (default), then the object is copied. Otherwise, a copy will
  653. only be made if __array__ returns a copy, if obj is a nested sequence,
  654. or if a copy is needed to satisfy any of the other requirements
  655. (`dtype`, `order`, etc.).
  656. order : {'K', 'A', 'C', 'F'}, optional
  657. Specify the memory layout of the array. If object is not an array, the
  658. newly created array will be in C order (row major) unless 'F' is
  659. specified, in which case it will be in Fortran order (column major).
  660. If object is an array the following holds.
  661. ===== ========= ===================================================
  662. order no copy copy=True
  663. ===== ========= ===================================================
  664. 'K' unchanged F & C order preserved, otherwise most similar order
  665. 'A' unchanged F order if input is F and not C, otherwise C order
  666. 'C' C order C order
  667. 'F' F order F order
  668. ===== ========= ===================================================
  669. When ``copy=False`` and a copy is made for other reasons, the result is
  670. the same as if ``copy=True``, with some exceptions for `A`, see the
  671. Notes section. The default order is 'K'.
  672. subok : bool, optional
  673. If True, then sub-classes will be passed-through, otherwise
  674. the returned array will be forced to be a base-class array (default).
  675. ndmin : int, optional
  676. Specifies the minimum number of dimensions that the resulting
  677. array should have. Ones will be pre-pended to the shape as
  678. needed to meet this requirement.
  679. ${ARRAY_FUNCTION_LIKE}
  680. .. versionadded:: 1.20.0
  681. Returns
  682. -------
  683. out : ndarray
  684. An array object satisfying the specified requirements.
  685. See Also
  686. --------
  687. empty_like : Return an empty array with shape and type of input.
  688. ones_like : Return an array of ones with shape and type of input.
  689. zeros_like : Return an array of zeros with shape and type of input.
  690. full_like : Return a new array with shape of input filled with value.
  691. empty : Return a new uninitialized array.
  692. ones : Return a new array setting values to one.
  693. zeros : Return a new array setting values to zero.
  694. full : Return a new array of given shape filled with value.
  695. Notes
  696. -----
  697. When order is 'A' and `object` is an array in neither 'C' nor 'F' order,
  698. and a copy is forced by a change in dtype, then the order of the result is
  699. not necessarily 'C' as expected. This is likely a bug.
  700. Examples
  701. --------
  702. >>> np.array([1, 2, 3])
  703. array([1, 2, 3])
  704. Upcasting:
  705. >>> np.array([1, 2, 3.0])
  706. array([ 1., 2., 3.])
  707. More than one dimension:
  708. >>> np.array([[1, 2], [3, 4]])
  709. array([[1, 2],
  710. [3, 4]])
  711. Minimum dimensions 2:
  712. >>> np.array([1, 2, 3], ndmin=2)
  713. array([[1, 2, 3]])
  714. Type provided:
  715. >>> np.array([1, 2, 3], dtype=complex)
  716. array([ 1.+0.j, 2.+0.j, 3.+0.j])
  717. Data-type consisting of more than one element:
  718. >>> x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')])
  719. >>> x['a']
  720. array([1, 3])
  721. Creating an array from sub-classes:
  722. >>> np.array(np.mat('1 2; 3 4'))
  723. array([[1, 2],
  724. [3, 4]])
  725. >>> np.array(np.mat('1 2; 3 4'), subok=True)
  726. matrix([[1, 2],
  727. [3, 4]])
  728. """.replace(
  729. "${ARRAY_FUNCTION_LIKE}",
  730. array_function_like_doc,
  731. ))
  732. add_newdoc('numpy.core.multiarray', 'empty',
  733. """
  734. empty(shape, dtype=float, order='C', *, like=None)
  735. Return a new array of given shape and type, without initializing entries.
  736. Parameters
  737. ----------
  738. shape : int or tuple of int
  739. Shape of the empty array, e.g., ``(2, 3)`` or ``2``.
  740. dtype : data-type, optional
  741. Desired output data-type for the array, e.g, `numpy.int8`. Default is
  742. `numpy.float64`.
  743. order : {'C', 'F'}, optional, default: 'C'
  744. Whether to store multi-dimensional data in row-major
  745. (C-style) or column-major (Fortran-style) order in
  746. memory.
  747. ${ARRAY_FUNCTION_LIKE}
  748. .. versionadded:: 1.20.0
  749. Returns
  750. -------
  751. out : ndarray
  752. Array of uninitialized (arbitrary) data of the given shape, dtype, and
  753. order. Object arrays will be initialized to None.
  754. See Also
  755. --------
  756. empty_like : Return an empty array with shape and type of input.
  757. ones : Return a new array setting values to one.
  758. zeros : Return a new array setting values to zero.
  759. full : Return a new array of given shape filled with value.
  760. Notes
  761. -----
  762. `empty`, unlike `zeros`, does not set the array values to zero,
  763. and may therefore be marginally faster. On the other hand, it requires
  764. the user to manually set all the values in the array, and should be
  765. used with caution.
  766. Examples
  767. --------
  768. >>> np.empty([2, 2])
  769. array([[ -9.74499359e+001, 6.69583040e-309],
  770. [ 2.13182611e-314, 3.06959433e-309]]) #uninitialized
  771. >>> np.empty([2, 2], dtype=int)
  772. array([[-1073741821, -1067949133],
  773. [ 496041986, 19249760]]) #uninitialized
  774. """.replace(
  775. "${ARRAY_FUNCTION_LIKE}",
  776. array_function_like_doc,
  777. ))
  778. add_newdoc('numpy.core.multiarray', 'scalar',
  779. """
  780. scalar(dtype, obj)
  781. Return a new scalar array of the given type initialized with obj.
  782. This function is meant mainly for pickle support. `dtype` must be a
  783. valid data-type descriptor. If `dtype` corresponds to an object
  784. descriptor, then `obj` can be any object, otherwise `obj` must be a
  785. string. If `obj` is not given, it will be interpreted as None for object
  786. type and as zeros for all other types.
  787. """)
  788. add_newdoc('numpy.core.multiarray', 'zeros',
  789. """
  790. zeros(shape, dtype=float, order='C', *, like=None)
  791. Return a new array of given shape and type, filled with zeros.
  792. Parameters
  793. ----------
  794. shape : int or tuple of ints
  795. Shape of the new array, e.g., ``(2, 3)`` or ``2``.
  796. dtype : data-type, optional
  797. The desired data-type for the array, e.g., `numpy.int8`. Default is
  798. `numpy.float64`.
  799. order : {'C', 'F'}, optional, default: 'C'
  800. Whether to store multi-dimensional data in row-major
  801. (C-style) or column-major (Fortran-style) order in
  802. memory.
  803. ${ARRAY_FUNCTION_LIKE}
  804. .. versionadded:: 1.20.0
  805. Returns
  806. -------
  807. out : ndarray
  808. Array of zeros with the given shape, dtype, and order.
  809. See Also
  810. --------
  811. zeros_like : Return an array of zeros with shape and type of input.
  812. empty : Return a new uninitialized array.
  813. ones : Return a new array setting values to one.
  814. full : Return a new array of given shape filled with value.
  815. Examples
  816. --------
  817. >>> np.zeros(5)
  818. array([ 0., 0., 0., 0., 0.])
  819. >>> np.zeros((5,), dtype=int)
  820. array([0, 0, 0, 0, 0])
  821. >>> np.zeros((2, 1))
  822. array([[ 0.],
  823. [ 0.]])
  824. >>> s = (2,2)
  825. >>> np.zeros(s)
  826. array([[ 0., 0.],
  827. [ 0., 0.]])
  828. >>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) # custom dtype
  829. array([(0, 0), (0, 0)],
  830. dtype=[('x', '<i4'), ('y', '<i4')])
  831. """.replace(
  832. "${ARRAY_FUNCTION_LIKE}",
  833. array_function_like_doc,
  834. ))
  835. add_newdoc('numpy.core.multiarray', 'set_typeDict',
  836. """set_typeDict(dict)
  837. Set the internal dictionary that can look up an array type using a
  838. registered code.
  839. """)
  840. add_newdoc('numpy.core.multiarray', 'fromstring',
  841. """
  842. fromstring(string, dtype=float, count=-1, sep='', *, like=None)
  843. A new 1-D array initialized from text data in a string.
  844. Parameters
  845. ----------
  846. string : str
  847. A string containing the data.
  848. dtype : data-type, optional
  849. The data type of the array; default: float. For binary input data,
  850. the data must be in exactly this format. Most builtin numeric types are
  851. supported and extension types may be supported.
  852. .. versionadded:: 1.18.0
  853. Complex dtypes.
  854. count : int, optional
  855. Read this number of `dtype` elements from the data. If this is
  856. negative (the default), the count will be determined from the
  857. length of the data.
  858. sep : str, optional
  859. The string separating numbers in the data; extra whitespace between
  860. elements is also ignored.
  861. .. deprecated:: 1.14
  862. Passing ``sep=''``, the default, is deprecated since it will
  863. trigger the deprecated binary mode of this function. This mode
  864. interprets `string` as binary bytes, rather than ASCII text with
  865. decimal numbers, an operation which is better spelt
  866. ``frombuffer(string, dtype, count)``. If `string` contains unicode
  867. text, the binary mode of `fromstring` will first encode it into
  868. bytes using either utf-8 (python 3) or the default encoding
  869. (python 2), neither of which produce sane results.
  870. ${ARRAY_FUNCTION_LIKE}
  871. .. versionadded:: 1.20.0
  872. Returns
  873. -------
  874. arr : ndarray
  875. The constructed array.
  876. Raises
  877. ------
  878. ValueError
  879. If the string is not the correct size to satisfy the requested
  880. `dtype` and `count`.
  881. See Also
  882. --------
  883. frombuffer, fromfile, fromiter
  884. Examples
  885. --------
  886. >>> np.fromstring('1 2', dtype=int, sep=' ')
  887. array([1, 2])
  888. >>> np.fromstring('1, 2', dtype=int, sep=',')
  889. array([1, 2])
  890. """.replace(
  891. "${ARRAY_FUNCTION_LIKE}",
  892. array_function_like_doc,
  893. ))
  894. add_newdoc('numpy.core.multiarray', 'compare_chararrays',
  895. """
  896. compare_chararrays(a, b, cmp_op, rstrip)
  897. Performs element-wise comparison of two string arrays using the
  898. comparison operator specified by `cmp_op`.
  899. Parameters
  900. ----------
  901. a, b : array_like
  902. Arrays to be compared.
  903. cmp_op : {"<", "<=", "==", ">=", ">", "!="}
  904. Type of comparison.
  905. rstrip : Boolean
  906. If True, the spaces at the end of Strings are removed before the comparison.
  907. Returns
  908. -------
  909. out : ndarray
  910. The output array of type Boolean with the same shape as a and b.
  911. Raises
  912. ------
  913. ValueError
  914. If `cmp_op` is not valid.
  915. TypeError
  916. If at least one of `a` or `b` is a non-string array
  917. Examples
  918. --------
  919. >>> a = np.array(["a", "b", "cde"])
  920. >>> b = np.array(["a", "a", "dec"])
  921. >>> np.compare_chararrays(a, b, ">", True)
  922. array([False, True, False])
  923. """)
  924. add_newdoc('numpy.core.multiarray', 'fromiter',
  925. """
  926. fromiter(iterable, dtype, count=-1, *, like=None)
  927. Create a new 1-dimensional array from an iterable object.
  928. Parameters
  929. ----------
  930. iterable : iterable object
  931. An iterable object providing data for the array.
  932. dtype : data-type
  933. The data-type of the returned array.
  934. count : int, optional
  935. The number of items to read from *iterable*. The default is -1,
  936. which means all data is read.
  937. ${ARRAY_FUNCTION_LIKE}
  938. .. versionadded:: 1.20.0
  939. Returns
  940. -------
  941. out : ndarray
  942. The output array.
  943. Notes
  944. -----
  945. Specify `count` to improve performance. It allows ``fromiter`` to
  946. pre-allocate the output array, instead of resizing it on demand.
  947. Examples
  948. --------
  949. >>> iterable = (x*x for x in range(5))
  950. >>> np.fromiter(iterable, float)
  951. array([ 0., 1., 4., 9., 16.])
  952. """.replace(
  953. "${ARRAY_FUNCTION_LIKE}",
  954. array_function_like_doc,
  955. ))
  956. add_newdoc('numpy.core.multiarray', 'fromfile',
  957. """
  958. fromfile(file, dtype=float, count=-1, sep='', offset=0, *, like=None)
  959. Construct an array from data in a text or binary file.
  960. A highly efficient way of reading binary data with a known data-type,
  961. as well as parsing simply formatted text files. Data written using the
  962. `tofile` method can be read using this function.
  963. Parameters
  964. ----------
  965. file : file or str or Path
  966. Open file object or filename.
  967. .. versionchanged:: 1.17.0
  968. `pathlib.Path` objects are now accepted.
  969. dtype : data-type
  970. Data type of the returned array.
  971. For binary files, it is used to determine the size and byte-order
  972. of the items in the file.
  973. Most builtin numeric types are supported and extension types may be supported.
  974. .. versionadded:: 1.18.0
  975. Complex dtypes.
  976. count : int
  977. Number of items to read. ``-1`` means all items (i.e., the complete
  978. file).
  979. sep : str
  980. Separator between items if file is a text file.
  981. Empty ("") separator means the file should be treated as binary.
  982. Spaces (" ") in the separator match zero or more whitespace characters.
  983. A separator consisting only of spaces must match at least one
  984. whitespace.
  985. offset : int
  986. The offset (in bytes) from the file's current position. Defaults to 0.
  987. Only permitted for binary files.
  988. .. versionadded:: 1.17.0
  989. ${ARRAY_FUNCTION_LIKE}
  990. .. versionadded:: 1.20.0
  991. See also
  992. --------
  993. load, save
  994. ndarray.tofile
  995. loadtxt : More flexible way of loading data from a text file.
  996. Notes
  997. -----
  998. Do not rely on the combination of `tofile` and `fromfile` for
  999. data storage, as the binary files generated are not platform
  1000. independent. In particular, no byte-order or data-type information is
  1001. saved. Data can be stored in the platform independent ``.npy`` format
  1002. using `save` and `load` instead.
  1003. Examples
  1004. --------
  1005. Construct an ndarray:
  1006. >>> dt = np.dtype([('time', [('min', np.int64), ('sec', np.int64)]),
  1007. ... ('temp', float)])
  1008. >>> x = np.zeros((1,), dtype=dt)
  1009. >>> x['time']['min'] = 10; x['temp'] = 98.25
  1010. >>> x
  1011. array([((10, 0), 98.25)],
  1012. dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')])
  1013. Save the raw data to disk:
  1014. >>> import tempfile
  1015. >>> fname = tempfile.mkstemp()[1]
  1016. >>> x.tofile(fname)
  1017. Read the raw data from disk:
  1018. >>> np.fromfile(fname, dtype=dt)
  1019. array([((10, 0), 98.25)],
  1020. dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')])
  1021. The recommended way to store and load data:
  1022. >>> np.save(fname, x)
  1023. >>> np.load(fname + '.npy')
  1024. array([((10, 0), 98.25)],
  1025. dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')])
  1026. """.replace(
  1027. "${ARRAY_FUNCTION_LIKE}",
  1028. array_function_like_doc,
  1029. ))
  1030. add_newdoc('numpy.core.multiarray', 'frombuffer',
  1031. """
  1032. frombuffer(buffer, dtype=float, count=-1, offset=0, *, like=None)
  1033. Interpret a buffer as a 1-dimensional array.
  1034. Parameters
  1035. ----------
  1036. buffer : buffer_like
  1037. An object that exposes the buffer interface.
  1038. dtype : data-type, optional
  1039. Data-type of the returned array; default: float.
  1040. count : int, optional
  1041. Number of items to read. ``-1`` means all data in the buffer.
  1042. offset : int, optional
  1043. Start reading the buffer from this offset (in bytes); default: 0.
  1044. ${ARRAY_FUNCTION_LIKE}
  1045. .. versionadded:: 1.20.0
  1046. Notes
  1047. -----
  1048. If the buffer has data that is not in machine byte-order, this should
  1049. be specified as part of the data-type, e.g.::
  1050. >>> dt = np.dtype(int)
  1051. >>> dt = dt.newbyteorder('>')
  1052. >>> np.frombuffer(buf, dtype=dt) # doctest: +SKIP
  1053. The data of the resulting array will not be byteswapped, but will be
  1054. interpreted correctly.
  1055. Examples
  1056. --------
  1057. >>> s = b'hello world'
  1058. >>> np.frombuffer(s, dtype='S1', count=5, offset=6)
  1059. array([b'w', b'o', b'r', b'l', b'd'], dtype='|S1')
  1060. >>> np.frombuffer(b'\\x01\\x02', dtype=np.uint8)
  1061. array([1, 2], dtype=uint8)
  1062. >>> np.frombuffer(b'\\x01\\x02\\x03\\x04\\x05', dtype=np.uint8, count=3)
  1063. array([1, 2, 3], dtype=uint8)
  1064. """.replace(
  1065. "${ARRAY_FUNCTION_LIKE}",
  1066. array_function_like_doc,
  1067. ))
  1068. add_newdoc('numpy.core', 'fastCopyAndTranspose',
  1069. """_fastCopyAndTranspose(a)""")
  1070. add_newdoc('numpy.core.multiarray', 'correlate',
  1071. """cross_correlate(a,v, mode=0)""")
  1072. add_newdoc('numpy.core.multiarray', 'arange',
  1073. """
  1074. arange([start,] stop[, step,], dtype=None, *, like=None)
  1075. Return evenly spaced values within a given interval.
  1076. Values are generated within the half-open interval ``[start, stop)``
  1077. (in other words, the interval including `start` but excluding `stop`).
  1078. For integer arguments the function is equivalent to the Python built-in
  1079. `range` function, but returns an ndarray rather than a list.
  1080. When using a non-integer step, such as 0.1, the results will often not
  1081. be consistent. It is better to use `numpy.linspace` for these cases.
  1082. Parameters
  1083. ----------
  1084. start : integer or real, optional
  1085. Start of interval. The interval includes this value. The default
  1086. start value is 0.
  1087. stop : integer or real
  1088. End of interval. The interval does not include this value, except
  1089. in some cases where `step` is not an integer and floating point
  1090. round-off affects the length of `out`.
  1091. step : integer or real, optional
  1092. Spacing between values. For any output `out`, this is the distance
  1093. between two adjacent values, ``out[i+1] - out[i]``. The default
  1094. step size is 1. If `step` is specified as a position argument,
  1095. `start` must also be given.
  1096. dtype : dtype
  1097. The type of the output array. If `dtype` is not given, infer the data
  1098. type from the other input arguments.
  1099. ${ARRAY_FUNCTION_LIKE}
  1100. .. versionadded:: 1.20.0
  1101. Returns
  1102. -------
  1103. arange : ndarray
  1104. Array of evenly spaced values.
  1105. For floating point arguments, the length of the result is
  1106. ``ceil((stop - start)/step)``. Because of floating point overflow,
  1107. this rule may result in the last element of `out` being greater
  1108. than `stop`.
  1109. See Also
  1110. --------
  1111. numpy.linspace : Evenly spaced numbers with careful handling of endpoints.
  1112. numpy.ogrid: Arrays of evenly spaced numbers in N-dimensions.
  1113. numpy.mgrid: Grid-shaped arrays of evenly spaced numbers in N-dimensions.
  1114. Examples
  1115. --------
  1116. >>> np.arange(3)
  1117. array([0, 1, 2])
  1118. >>> np.arange(3.0)
  1119. array([ 0., 1., 2.])
  1120. >>> np.arange(3,7)
  1121. array([3, 4, 5, 6])
  1122. >>> np.arange(3,7,2)
  1123. array([3, 5])
  1124. """.replace(
  1125. "${ARRAY_FUNCTION_LIKE}",
  1126. array_function_like_doc,
  1127. ))
  1128. add_newdoc('numpy.core.multiarray', '_get_ndarray_c_version',
  1129. """_get_ndarray_c_version()
  1130. Return the compile time NPY_VERSION (formerly called NDARRAY_VERSION) number.
  1131. """)
  1132. add_newdoc('numpy.core.multiarray', '_reconstruct',
  1133. """_reconstruct(subtype, shape, dtype)
  1134. Construct an empty array. Used by Pickles.
  1135. """)
  1136. add_newdoc('numpy.core.multiarray', 'set_string_function',
  1137. """
  1138. set_string_function(f, repr=1)
  1139. Internal method to set a function to be used when pretty printing arrays.
  1140. """)
  1141. add_newdoc('numpy.core.multiarray', 'set_numeric_ops',
  1142. """
  1143. set_numeric_ops(op1=func1, op2=func2, ...)
  1144. Set numerical operators for array objects.
  1145. .. deprecated:: 1.16
  1146. For the general case, use :c:func:`PyUFunc_ReplaceLoopBySignature`.
  1147. For ndarray subclasses, define the ``__array_ufunc__`` method and
  1148. override the relevant ufunc.
  1149. Parameters
  1150. ----------
  1151. op1, op2, ... : callable
  1152. Each ``op = func`` pair describes an operator to be replaced.
  1153. For example, ``add = lambda x, y: np.add(x, y) % 5`` would replace
  1154. addition by modulus 5 addition.
  1155. Returns
  1156. -------
  1157. saved_ops : list of callables
  1158. A list of all operators, stored before making replacements.
  1159. Notes
  1160. -----
  1161. .. WARNING::
  1162. Use with care! Incorrect usage may lead to memory errors.
  1163. A function replacing an operator cannot make use of that operator.
  1164. For example, when replacing add, you may not use ``+``. Instead,
  1165. directly call ufuncs.
  1166. Examples
  1167. --------
  1168. >>> def add_mod5(x, y):
  1169. ... return np.add(x, y) % 5
  1170. ...
  1171. >>> old_funcs = np.set_numeric_ops(add=add_mod5)
  1172. >>> x = np.arange(12).reshape((3, 4))
  1173. >>> x + x
  1174. array([[0, 2, 4, 1],
  1175. [3, 0, 2, 4],
  1176. [1, 3, 0, 2]])
  1177. >>> ignore = np.set_numeric_ops(**old_funcs) # restore operators
  1178. """)
  1179. add_newdoc('numpy.core.multiarray', 'promote_types',
  1180. """
  1181. promote_types(type1, type2)
  1182. Returns the data type with the smallest size and smallest scalar
  1183. kind to which both ``type1`` and ``type2`` may be safely cast.
  1184. The returned data type is always in native byte order.
  1185. This function is symmetric, but rarely associative.
  1186. Parameters
  1187. ----------
  1188. type1 : dtype or dtype specifier
  1189. First data type.
  1190. type2 : dtype or dtype specifier
  1191. Second data type.
  1192. Returns
  1193. -------
  1194. out : dtype
  1195. The promoted data type.
  1196. Notes
  1197. -----
  1198. .. versionadded:: 1.6.0
  1199. Starting in NumPy 1.9, promote_types function now returns a valid string
  1200. length when given an integer or float dtype as one argument and a string
  1201. dtype as another argument. Previously it always returned the input string
  1202. dtype, even if it wasn't long enough to store the max integer/float value
  1203. converted to a string.
  1204. See Also
  1205. --------
  1206. result_type, dtype, can_cast
  1207. Examples
  1208. --------
  1209. >>> np.promote_types('f4', 'f8')
  1210. dtype('float64')
  1211. >>> np.promote_types('i8', 'f4')
  1212. dtype('float64')
  1213. >>> np.promote_types('>i8', '<c8')
  1214. dtype('complex128')
  1215. >>> np.promote_types('i4', 'S8')
  1216. dtype('S11')
  1217. An example of a non-associative case:
  1218. >>> p = np.promote_types
  1219. >>> p('S', p('i1', 'u1'))
  1220. dtype('S6')
  1221. >>> p(p('S', 'i1'), 'u1')
  1222. dtype('S4')
  1223. """)
  1224. add_newdoc('numpy.core.multiarray', 'c_einsum',
  1225. """
  1226. c_einsum(subscripts, *operands, out=None, dtype=None, order='K',
  1227. casting='safe')
  1228. *This documentation shadows that of the native python implementation of the `einsum` function,
  1229. except all references and examples related to the `optimize` argument (v 0.12.0) have been removed.*
  1230. Evaluates the Einstein summation convention on the operands.
  1231. Using the Einstein summation convention, many common multi-dimensional,
  1232. linear algebraic array operations can be represented in a simple fashion.
  1233. In *implicit* mode `einsum` computes these values.
  1234. In *explicit* mode, `einsum` provides further flexibility to compute
  1235. other array operations that might not be considered classical Einstein
  1236. summation operations, by disabling, or forcing summation over specified
  1237. subscript labels.
  1238. See the notes and examples for clarification.
  1239. Parameters
  1240. ----------
  1241. subscripts : str
  1242. Specifies the subscripts for summation as comma separated list of
  1243. subscript labels. An implicit (classical Einstein summation)
  1244. calculation is performed unless the explicit indicator '->' is
  1245. included as well as subscript labels of the precise output form.
  1246. operands : list of array_like
  1247. These are the arrays for the operation.
  1248. out : ndarray, optional
  1249. If provided, the calculation is done into this array.
  1250. dtype : {data-type, None}, optional
  1251. If provided, forces the calculation to use the data type specified.
  1252. Note that you may have to also give a more liberal `casting`
  1253. parameter to allow the conversions. Default is None.
  1254. order : {'C', 'F', 'A', 'K'}, optional
  1255. Controls the memory layout of the output. 'C' means it should
  1256. be C contiguous. 'F' means it should be Fortran contiguous,
  1257. 'A' means it should be 'F' if the inputs are all 'F', 'C' otherwise.
  1258. 'K' means it should be as close to the layout of the inputs as
  1259. is possible, including arbitrarily permuted axes.
  1260. Default is 'K'.
  1261. casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
  1262. Controls what kind of data casting may occur. Setting this to
  1263. 'unsafe' is not recommended, as it can adversely affect accumulations.
  1264. * 'no' means the data types should not be cast at all.
  1265. * 'equiv' means only byte-order changes are allowed.
  1266. * 'safe' means only casts which can preserve values are allowed.
  1267. * 'same_kind' means only safe casts or casts within a kind,
  1268. like float64 to float32, are allowed.
  1269. * 'unsafe' means any data conversions may be done.
  1270. Default is 'safe'.
  1271. optimize : {False, True, 'greedy', 'optimal'}, optional
  1272. Controls if intermediate optimization should occur. No optimization
  1273. will occur if False and True will default to the 'greedy' algorithm.
  1274. Also accepts an explicit contraction list from the ``np.einsum_path``
  1275. function. See ``np.einsum_path`` for more details. Defaults to False.
  1276. Returns
  1277. -------
  1278. output : ndarray
  1279. The calculation based on the Einstein summation convention.
  1280. See Also
  1281. --------
  1282. einsum_path, dot, inner, outer, tensordot, linalg.multi_dot
  1283. Notes
  1284. -----
  1285. .. versionadded:: 1.6.0
  1286. The Einstein summation convention can be used to compute
  1287. many multi-dimensional, linear algebraic array operations. `einsum`
  1288. provides a succinct way of representing these.
  1289. A non-exhaustive list of these operations,
  1290. which can be computed by `einsum`, is shown below along with examples:
  1291. * Trace of an array, :py:func:`numpy.trace`.
  1292. * Return a diagonal, :py:func:`numpy.diag`.
  1293. * Array axis summations, :py:func:`numpy.sum`.
  1294. * Transpositions and permutations, :py:func:`numpy.transpose`.
  1295. * Matrix multiplication and dot product, :py:func:`numpy.matmul` :py:func:`numpy.dot`.
  1296. * Vector inner and outer products, :py:func:`numpy.inner` :py:func:`numpy.outer`.
  1297. * Broadcasting, element-wise and scalar multiplication, :py:func:`numpy.multiply`.
  1298. * Tensor contractions, :py:func:`numpy.tensordot`.
  1299. * Chained array operations, in efficient calculation order, :py:func:`numpy.einsum_path`.
  1300. The subscripts string is a comma-separated list of subscript labels,
  1301. where each label refers to a dimension of the corresponding operand.
  1302. Whenever a label is repeated it is summed, so ``np.einsum('i,i', a, b)``
  1303. is equivalent to :py:func:`np.inner(a,b) <numpy.inner>`. If a label
  1304. appears only once, it is not summed, so ``np.einsum('i', a)`` produces a
  1305. view of ``a`` with no changes. A further example ``np.einsum('ij,jk', a, b)``
  1306. describes traditional matrix multiplication and is equivalent to
  1307. :py:func:`np.matmul(a,b) <numpy.matmul>`. Repeated subscript labels in one
  1308. operand take the diagonal. For example, ``np.einsum('ii', a)`` is equivalent
  1309. to :py:func:`np.trace(a) <numpy.trace>`.
  1310. In *implicit mode*, the chosen subscripts are important
  1311. since the axes of the output are reordered alphabetically. This
  1312. means that ``np.einsum('ij', a)`` doesn't affect a 2D array, while
  1313. ``np.einsum('ji', a)`` takes its transpose. Additionally,
  1314. ``np.einsum('ij,jk', a, b)`` returns a matrix multiplication, while,
  1315. ``np.einsum('ij,jh', a, b)`` returns the transpose of the
  1316. multiplication since subscript 'h' precedes subscript 'i'.
  1317. In *explicit mode* the output can be directly controlled by
  1318. specifying output subscript labels. This requires the
  1319. identifier '->' as well as the list of output subscript labels.
  1320. This feature increases the flexibility of the function since
  1321. summing can be disabled or forced when required. The call
  1322. ``np.einsum('i->', a)`` is like :py:func:`np.sum(a, axis=-1) <numpy.sum>`,
  1323. and ``np.einsum('ii->i', a)`` is like :py:func:`np.diag(a) <numpy.diag>`.
  1324. The difference is that `einsum` does not allow broadcasting by default.
  1325. Additionally ``np.einsum('ij,jh->ih', a, b)`` directly specifies the
  1326. order of the output subscript labels and therefore returns matrix
  1327. multiplication, unlike the example above in implicit mode.
  1328. To enable and control broadcasting, use an ellipsis. Default
  1329. NumPy-style broadcasting is done by adding an ellipsis
  1330. to the left of each term, like ``np.einsum('...ii->...i', a)``.
  1331. To take the trace along the first and last axes,
  1332. you can do ``np.einsum('i...i', a)``, or to do a matrix-matrix
  1333. product with the left-most indices instead of rightmost, one can do
  1334. ``np.einsum('ij...,jk...->ik...', a, b)``.
  1335. When there is only one operand, no axes are summed, and no output
  1336. parameter is provided, a view into the operand is returned instead
  1337. of a new array. Thus, taking the diagonal as ``np.einsum('ii->i', a)``
  1338. produces a view (changed in version 1.10.0).
  1339. `einsum` also provides an alternative way to provide the subscripts
  1340. and operands as ``einsum(op0, sublist0, op1, sublist1, ..., [sublistout])``.
  1341. If the output shape is not provided in this format `einsum` will be
  1342. calculated in implicit mode, otherwise it will be performed explicitly.
  1343. The examples below have corresponding `einsum` calls with the two
  1344. parameter methods.
  1345. .. versionadded:: 1.10.0
  1346. Views returned from einsum are now writeable whenever the input array
  1347. is writeable. For example, ``np.einsum('ijk...->kji...', a)`` will now
  1348. have the same effect as :py:func:`np.swapaxes(a, 0, 2) <numpy.swapaxes>`
  1349. and ``np.einsum('ii->i', a)`` will return a writeable view of the diagonal
  1350. of a 2D array.
  1351. Examples
  1352. --------
  1353. >>> a = np.arange(25).reshape(5,5)
  1354. >>> b = np.arange(5)
  1355. >>> c = np.arange(6).reshape(2,3)
  1356. Trace of a matrix:
  1357. >>> np.einsum('ii', a)
  1358. 60
  1359. >>> np.einsum(a, [0,0])
  1360. 60
  1361. >>> np.trace(a)
  1362. 60
  1363. Extract the diagonal (requires explicit form):
  1364. >>> np.einsum('ii->i', a)
  1365. array([ 0, 6, 12, 18, 24])
  1366. >>> np.einsum(a, [0,0], [0])
  1367. array([ 0, 6, 12, 18, 24])
  1368. >>> np.diag(a)
  1369. array([ 0, 6, 12, 18, 24])
  1370. Sum over an axis (requires explicit form):
  1371. >>> np.einsum('ij->i', a)
  1372. array([ 10, 35, 60, 85, 110])
  1373. >>> np.einsum(a, [0,1], [0])
  1374. array([ 10, 35, 60, 85, 110])
  1375. >>> np.sum(a, axis=1)
  1376. array([ 10, 35, 60, 85, 110])
  1377. For higher dimensional arrays summing a single axis can be done with ellipsis:
  1378. >>> np.einsum('...j->...', a)
  1379. array([ 10, 35, 60, 85, 110])
  1380. >>> np.einsum(a, [Ellipsis,1], [Ellipsis])
  1381. array([ 10, 35, 60, 85, 110])
  1382. Compute a matrix transpose, or reorder any number of axes:
  1383. >>> np.einsum('ji', c)
  1384. array([[0, 3],
  1385. [1, 4],
  1386. [2, 5]])
  1387. >>> np.einsum('ij->ji', c)
  1388. array([[0, 3],
  1389. [1, 4],
  1390. [2, 5]])
  1391. >>> np.einsum(c, [1,0])
  1392. array([[0, 3],
  1393. [1, 4],
  1394. [2, 5]])
  1395. >>> np.transpose(c)
  1396. array([[0, 3],
  1397. [1, 4],
  1398. [2, 5]])
  1399. Vector inner products:
  1400. >>> np.einsum('i,i', b, b)
  1401. 30
  1402. >>> np.einsum(b, [0], b, [0])
  1403. 30
  1404. >>> np.inner(b,b)
  1405. 30
  1406. Matrix vector multiplication:
  1407. >>> np.einsum('ij,j', a, b)
  1408. array([ 30, 80, 130, 180, 230])
  1409. >>> np.einsum(a, [0,1], b, [1])
  1410. array([ 30, 80, 130, 180, 230])
  1411. >>> np.dot(a, b)
  1412. array([ 30, 80, 130, 180, 230])
  1413. >>> np.einsum('...j,j', a, b)
  1414. array([ 30, 80, 130, 180, 230])
  1415. Broadcasting and scalar multiplication:
  1416. >>> np.einsum('..., ...', 3, c)
  1417. array([[ 0, 3, 6],
  1418. [ 9, 12, 15]])
  1419. >>> np.einsum(',ij', 3, c)
  1420. array([[ 0, 3, 6],
  1421. [ 9, 12, 15]])
  1422. >>> np.einsum(3, [Ellipsis], c, [Ellipsis])
  1423. array([[ 0, 3, 6],
  1424. [ 9, 12, 15]])
  1425. >>> np.multiply(3, c)
  1426. array([[ 0, 3, 6],
  1427. [ 9, 12, 15]])
  1428. Vector outer product:
  1429. >>> np.einsum('i,j', np.arange(2)+1, b)
  1430. array([[0, 1, 2, 3, 4],
  1431. [0, 2, 4, 6, 8]])
  1432. >>> np.einsum(np.arange(2)+1, [0], b, [1])
  1433. array([[0, 1, 2, 3, 4],
  1434. [0, 2, 4, 6, 8]])
  1435. >>> np.outer(np.arange(2)+1, b)
  1436. array([[0, 1, 2, 3, 4],
  1437. [0, 2, 4, 6, 8]])
  1438. Tensor contraction:
  1439. >>> a = np.arange(60.).reshape(3,4,5)
  1440. >>> b = np.arange(24.).reshape(4,3,2)
  1441. >>> np.einsum('ijk,jil->kl', a, b)
  1442. array([[ 4400., 4730.],
  1443. [ 4532., 4874.],
  1444. [ 4664., 5018.],
  1445. [ 4796., 5162.],
  1446. [ 4928., 5306.]])
  1447. >>> np.einsum(a, [0,1,2], b, [1,0,3], [2,3])
  1448. array([[ 4400., 4730.],
  1449. [ 4532., 4874.],
  1450. [ 4664., 5018.],
  1451. [ 4796., 5162.],
  1452. [ 4928., 5306.]])
  1453. >>> np.tensordot(a,b, axes=([1,0],[0,1]))
  1454. array([[ 4400., 4730.],
  1455. [ 4532., 4874.],
  1456. [ 4664., 5018.],
  1457. [ 4796., 5162.],
  1458. [ 4928., 5306.]])
  1459. Writeable returned arrays (since version 1.10.0):
  1460. >>> a = np.zeros((3, 3))
  1461. >>> np.einsum('ii->i', a)[:] = 1
  1462. >>> a
  1463. array([[ 1., 0., 0.],
  1464. [ 0., 1., 0.],
  1465. [ 0., 0., 1.]])
  1466. Example of ellipsis use:
  1467. >>> a = np.arange(6).reshape((3,2))
  1468. >>> b = np.arange(12).reshape((4,3))
  1469. >>> np.einsum('ki,jk->ij', a, b)
  1470. array([[10, 28, 46, 64],
  1471. [13, 40, 67, 94]])
  1472. >>> np.einsum('ki,...k->i...', a, b)
  1473. array([[10, 28, 46, 64],
  1474. [13, 40, 67, 94]])
  1475. >>> np.einsum('k...,jk', a, b)
  1476. array([[10, 28, 46, 64],
  1477. [13, 40, 67, 94]])
  1478. """)
  1479. ##############################################################################
  1480. #
  1481. # Documentation for ndarray attributes and methods
  1482. #
  1483. ##############################################################################
  1484. ##############################################################################
  1485. #
  1486. # ndarray object
  1487. #
  1488. ##############################################################################
  1489. add_newdoc('numpy.core.multiarray', 'ndarray',
  1490. """
  1491. ndarray(shape, dtype=float, buffer=None, offset=0,
  1492. strides=None, order=None)
  1493. An array object represents a multidimensional, homogeneous array
  1494. of fixed-size items. An associated data-type object describes the
  1495. format of each element in the array (its byte-order, how many bytes it
  1496. occupies in memory, whether it is an integer, a floating point number,
  1497. or something else, etc.)
  1498. Arrays should be constructed using `array`, `zeros` or `empty` (refer
  1499. to the See Also section below). The parameters given here refer to
  1500. a low-level method (`ndarray(...)`) for instantiating an array.
  1501. For more information, refer to the `numpy` module and examine the
  1502. methods and attributes of an array.
  1503. Parameters
  1504. ----------
  1505. (for the __new__ method; see Notes below)
  1506. shape : tuple of ints
  1507. Shape of created array.
  1508. dtype : data-type, optional
  1509. Any object that can be interpreted as a numpy data type.
  1510. buffer : object exposing buffer interface, optional
  1511. Used to fill the array with data.
  1512. offset : int, optional
  1513. Offset of array data in buffer.
  1514. strides : tuple of ints, optional
  1515. Strides of data in memory.
  1516. order : {'C', 'F'}, optional
  1517. Row-major (C-style) or column-major (Fortran-style) order.
  1518. Attributes
  1519. ----------
  1520. T : ndarray
  1521. Transpose of the array.
  1522. data : buffer
  1523. The array's elements, in memory.
  1524. dtype : dtype object
  1525. Describes the format of the elements in the array.
  1526. flags : dict
  1527. Dictionary containing information related to memory use, e.g.,
  1528. 'C_CONTIGUOUS', 'OWNDATA', 'WRITEABLE', etc.
  1529. flat : numpy.flatiter object
  1530. Flattened version of the array as an iterator. The iterator
  1531. allows assignments, e.g., ``x.flat = 3`` (See `ndarray.flat` for
  1532. assignment examples; TODO).
  1533. imag : ndarray
  1534. Imaginary part of the array.
  1535. real : ndarray
  1536. Real part of the array.
  1537. size : int
  1538. Number of elements in the array.
  1539. itemsize : int
  1540. The memory use of each array element in bytes.
  1541. nbytes : int
  1542. The total number of bytes required to store the array data,
  1543. i.e., ``itemsize * size``.
  1544. ndim : int
  1545. The array's number of dimensions.
  1546. shape : tuple of ints
  1547. Shape of the array.
  1548. strides : tuple of ints
  1549. The step-size required to move from one element to the next in
  1550. memory. For example, a contiguous ``(3, 4)`` array of type
  1551. ``int16`` in C-order has strides ``(8, 2)``. This implies that
  1552. to move from element to element in memory requires jumps of 2 bytes.
  1553. To move from row-to-row, one needs to jump 8 bytes at a time
  1554. (``2 * 4``).
  1555. ctypes : ctypes object
  1556. Class containing properties of the array needed for interaction
  1557. with ctypes.
  1558. base : ndarray
  1559. If the array is a view into another array, that array is its `base`
  1560. (unless that array is also a view). The `base` array is where the
  1561. array data is actually stored.
  1562. See Also
  1563. --------
  1564. array : Construct an array.
  1565. zeros : Create an array, each element of which is zero.
  1566. empty : Create an array, but leave its allocated memory unchanged (i.e.,
  1567. it contains "garbage").
  1568. dtype : Create a data-type.
  1569. Notes
  1570. -----
  1571. There are two modes of creating an array using ``__new__``:
  1572. 1. If `buffer` is None, then only `shape`, `dtype`, and `order`
  1573. are used.
  1574. 2. If `buffer` is an object exposing the buffer interface, then
  1575. all keywords are interpreted.
  1576. No ``__init__`` method is needed because the array is fully initialized
  1577. after the ``__new__`` method.
  1578. Examples
  1579. --------
  1580. These examples illustrate the low-level `ndarray` constructor. Refer
  1581. to the `See Also` section above for easier ways of constructing an
  1582. ndarray.
  1583. First mode, `buffer` is None:
  1584. >>> np.ndarray(shape=(2,2), dtype=float, order='F')
  1585. array([[0.0e+000, 0.0e+000], # random
  1586. [ nan, 2.5e-323]])
  1587. Second mode:
  1588. >>> np.ndarray((2,), buffer=np.array([1,2,3]),
  1589. ... offset=np.int_().itemsize,
  1590. ... dtype=int) # offset = 1*itemsize, i.e. skip first element
  1591. array([2, 3])
  1592. """)
  1593. ##############################################################################
  1594. #
  1595. # ndarray attributes
  1596. #
  1597. ##############################################################################
  1598. add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_interface__',
  1599. """Array protocol: Python side."""))
  1600. add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_finalize__',
  1601. """None."""))
  1602. add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_priority__',
  1603. """Array priority."""))
  1604. add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_struct__',
  1605. """Array protocol: C-struct side."""))
  1606. add_newdoc('numpy.core.multiarray', 'ndarray', ('base',
  1607. """
  1608. Base object if memory is from some other object.
  1609. Examples
  1610. --------
  1611. The base of an array that owns its memory is None:
  1612. >>> x = np.array([1,2,3,4])
  1613. >>> x.base is None
  1614. True
  1615. Slicing creates a view, whose memory is shared with x:
  1616. >>> y = x[2:]
  1617. >>> y.base is x
  1618. True
  1619. """))
  1620. add_newdoc('numpy.core.multiarray', 'ndarray', ('ctypes',
  1621. """
  1622. An object to simplify the interaction of the array with the ctypes
  1623. module.
  1624. This attribute creates an object that makes it easier to use arrays
  1625. when calling shared libraries with the ctypes module. The returned
  1626. object has, among others, data, shape, and strides attributes (see
  1627. Notes below) which themselves return ctypes objects that can be used
  1628. as arguments to a shared library.
  1629. Parameters
  1630. ----------
  1631. None
  1632. Returns
  1633. -------
  1634. c : Python object
  1635. Possessing attributes data, shape, strides, etc.
  1636. See Also
  1637. --------
  1638. numpy.ctypeslib
  1639. Notes
  1640. -----
  1641. Below are the public attributes of this object which were documented
  1642. in "Guide to NumPy" (we have omitted undocumented public attributes,
  1643. as well as documented private attributes):
  1644. .. autoattribute:: numpy.core._internal._ctypes.data
  1645. :noindex:
  1646. .. autoattribute:: numpy.core._internal._ctypes.shape
  1647. :noindex:
  1648. .. autoattribute:: numpy.core._internal._ctypes.strides
  1649. :noindex:
  1650. .. automethod:: numpy.core._internal._ctypes.data_as
  1651. :noindex:
  1652. .. automethod:: numpy.core._internal._ctypes.shape_as
  1653. :noindex:
  1654. .. automethod:: numpy.core._internal._ctypes.strides_as
  1655. :noindex:
  1656. If the ctypes module is not available, then the ctypes attribute
  1657. of array objects still returns something useful, but ctypes objects
  1658. are not returned and errors may be raised instead. In particular,
  1659. the object will still have the ``as_parameter`` attribute which will
  1660. return an integer equal to the data attribute.
  1661. Examples
  1662. --------
  1663. >>> import ctypes
  1664. >>> x = np.array([[0, 1], [2, 3]], dtype=np.int32)
  1665. >>> x
  1666. array([[0, 1],
  1667. [2, 3]], dtype=int32)
  1668. >>> x.ctypes.data
  1669. 31962608 # may vary
  1670. >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32))
  1671. <__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary
  1672. >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents
  1673. c_uint(0)
  1674. >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents
  1675. c_ulong(4294967296)
  1676. >>> x.ctypes.shape
  1677. <numpy.core._internal.c_long_Array_2 object at 0x7ff2fc1fce60> # may vary
  1678. >>> x.ctypes.strides
  1679. <numpy.core._internal.c_long_Array_2 object at 0x7ff2fc1ff320> # may vary
  1680. """))
  1681. add_newdoc('numpy.core.multiarray', 'ndarray', ('data',
  1682. """Python buffer object pointing to the start of the array's data."""))
  1683. add_newdoc('numpy.core.multiarray', 'ndarray', ('dtype',
  1684. """
  1685. Data-type of the array's elements.
  1686. Parameters
  1687. ----------
  1688. None
  1689. Returns
  1690. -------
  1691. d : numpy dtype object
  1692. See Also
  1693. --------
  1694. numpy.dtype
  1695. Examples
  1696. --------
  1697. >>> x
  1698. array([[0, 1],
  1699. [2, 3]])
  1700. >>> x.dtype
  1701. dtype('int32')
  1702. >>> type(x.dtype)
  1703. <type 'numpy.dtype'>
  1704. """))
  1705. add_newdoc('numpy.core.multiarray', 'ndarray', ('imag',
  1706. """
  1707. The imaginary part of the array.
  1708. Examples
  1709. --------
  1710. >>> x = np.sqrt([1+0j, 0+1j])
  1711. >>> x.imag
  1712. array([ 0. , 0.70710678])
  1713. >>> x.imag.dtype
  1714. dtype('float64')
  1715. """))
  1716. add_newdoc('numpy.core.multiarray', 'ndarray', ('itemsize',
  1717. """
  1718. Length of one array element in bytes.
  1719. Examples
  1720. --------
  1721. >>> x = np.array([1,2,3], dtype=np.float64)
  1722. >>> x.itemsize
  1723. 8
  1724. >>> x = np.array([1,2,3], dtype=np.complex128)
  1725. >>> x.itemsize
  1726. 16
  1727. """))
  1728. add_newdoc('numpy.core.multiarray', 'ndarray', ('flags',
  1729. """
  1730. Information about the memory layout of the array.
  1731. Attributes
  1732. ----------
  1733. C_CONTIGUOUS (C)
  1734. The data is in a single, C-style contiguous segment.
  1735. F_CONTIGUOUS (F)
  1736. The data is in a single, Fortran-style contiguous segment.
  1737. OWNDATA (O)
  1738. The array owns the memory it uses or borrows it from another object.
  1739. WRITEABLE (W)
  1740. The data area can be written to. Setting this to False locks
  1741. the data, making it read-only. A view (slice, etc.) inherits WRITEABLE
  1742. from its base array at creation time, but a view of a writeable
  1743. array may be subsequently locked while the base array remains writeable.
  1744. (The opposite is not true, in that a view of a locked array may not
  1745. be made writeable. However, currently, locking a base object does not
  1746. lock any views that already reference it, so under that circumstance it
  1747. is possible to alter the contents of a locked array via a previously
  1748. created writeable view onto it.) Attempting to change a non-writeable
  1749. array raises a RuntimeError exception.
  1750. ALIGNED (A)
  1751. The data and all elements are aligned appropriately for the hardware.
  1752. WRITEBACKIFCOPY (X)
  1753. This array is a copy of some other array. The C-API function
  1754. PyArray_ResolveWritebackIfCopy must be called before deallocating
  1755. to the base array will be updated with the contents of this array.
  1756. UPDATEIFCOPY (U)
  1757. (Deprecated, use WRITEBACKIFCOPY) This array is a copy of some other array.
  1758. When this array is
  1759. deallocated, the base array will be updated with the contents of
  1760. this array.
  1761. FNC
  1762. F_CONTIGUOUS and not C_CONTIGUOUS.
  1763. FORC
  1764. F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
  1765. BEHAVED (B)
  1766. ALIGNED and WRITEABLE.
  1767. CARRAY (CA)
  1768. BEHAVED and C_CONTIGUOUS.
  1769. FARRAY (FA)
  1770. BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.
  1771. Notes
  1772. -----
  1773. The `flags` object can be accessed dictionary-like (as in ``a.flags['WRITEABLE']``),
  1774. or by using lowercased attribute names (as in ``a.flags.writeable``). Short flag
  1775. names are only supported in dictionary access.
  1776. Only the WRITEBACKIFCOPY, UPDATEIFCOPY, WRITEABLE, and ALIGNED flags can be
  1777. changed by the user, via direct assignment to the attribute or dictionary
  1778. entry, or by calling `ndarray.setflags`.
  1779. The array flags cannot be set arbitrarily:
  1780. - UPDATEIFCOPY can only be set ``False``.
  1781. - WRITEBACKIFCOPY can only be set ``False``.
  1782. - ALIGNED can only be set ``True`` if the data is truly aligned.
  1783. - WRITEABLE can only be set ``True`` if the array owns its own memory
  1784. or the ultimate owner of the memory exposes a writeable buffer
  1785. interface or is a string.
  1786. Arrays can be both C-style and Fortran-style contiguous simultaneously.
  1787. This is clear for 1-dimensional arrays, but can also be true for higher
  1788. dimensional arrays.
  1789. Even for contiguous arrays a stride for a given dimension
  1790. ``arr.strides[dim]`` may be *arbitrary* if ``arr.shape[dim] == 1``
  1791. or the array has no elements.
  1792. It does *not* generally hold that ``self.strides[-1] == self.itemsize``
  1793. for C-style contiguous arrays or ``self.strides[0] == self.itemsize`` for
  1794. Fortran-style contiguous arrays is true.
  1795. """))
  1796. add_newdoc('numpy.core.multiarray', 'ndarray', ('flat',
  1797. """
  1798. A 1-D iterator over the array.
  1799. This is a `numpy.flatiter` instance, which acts similarly to, but is not
  1800. a subclass of, Python's built-in iterator object.
  1801. See Also
  1802. --------
  1803. flatten : Return a copy of the array collapsed into one dimension.
  1804. flatiter
  1805. Examples
  1806. --------
  1807. >>> x = np.arange(1, 7).reshape(2, 3)
  1808. >>> x
  1809. array([[1, 2, 3],
  1810. [4, 5, 6]])
  1811. >>> x.flat[3]
  1812. 4
  1813. >>> x.T
  1814. array([[1, 4],
  1815. [2, 5],
  1816. [3, 6]])
  1817. >>> x.T.flat[3]
  1818. 5
  1819. >>> type(x.flat)
  1820. <class 'numpy.flatiter'>
  1821. An assignment example:
  1822. >>> x.flat = 3; x
  1823. array([[3, 3, 3],
  1824. [3, 3, 3]])
  1825. >>> x.flat[[1,4]] = 1; x
  1826. array([[3, 1, 3],
  1827. [3, 1, 3]])
  1828. """))
  1829. add_newdoc('numpy.core.multiarray', 'ndarray', ('nbytes',
  1830. """
  1831. Total bytes consumed by the elements of the array.
  1832. Notes
  1833. -----
  1834. Does not include memory consumed by non-element attributes of the
  1835. array object.
  1836. Examples
  1837. --------
  1838. >>> x = np.zeros((3,5,2), dtype=np.complex128)
  1839. >>> x.nbytes
  1840. 480
  1841. >>> np.prod(x.shape) * x.itemsize
  1842. 480
  1843. """))
  1844. add_newdoc('numpy.core.multiarray', 'ndarray', ('ndim',
  1845. """
  1846. Number of array dimensions.
  1847. Examples
  1848. --------
  1849. >>> x = np.array([1, 2, 3])
  1850. >>> x.ndim
  1851. 1
  1852. >>> y = np.zeros((2, 3, 4))
  1853. >>> y.ndim
  1854. 3
  1855. """))
  1856. add_newdoc('numpy.core.multiarray', 'ndarray', ('real',
  1857. """
  1858. The real part of the array.
  1859. Examples
  1860. --------
  1861. >>> x = np.sqrt([1+0j, 0+1j])
  1862. >>> x.real
  1863. array([ 1. , 0.70710678])
  1864. >>> x.real.dtype
  1865. dtype('float64')
  1866. See Also
  1867. --------
  1868. numpy.real : equivalent function
  1869. """))
  1870. add_newdoc('numpy.core.multiarray', 'ndarray', ('shape',
  1871. """
  1872. Tuple of array dimensions.
  1873. The shape property is usually used to get the current shape of an array,
  1874. but may also be used to reshape the array in-place by assigning a tuple of
  1875. array dimensions to it. As with `numpy.reshape`, one of the new shape
  1876. dimensions can be -1, in which case its value is inferred from the size of
  1877. the array and the remaining dimensions. Reshaping an array in-place will
  1878. fail if a copy is required.
  1879. Examples
  1880. --------
  1881. >>> x = np.array([1, 2, 3, 4])
  1882. >>> x.shape
  1883. (4,)
  1884. >>> y = np.zeros((2, 3, 4))
  1885. >>> y.shape
  1886. (2, 3, 4)
  1887. >>> y.shape = (3, 8)
  1888. >>> y
  1889. array([[ 0., 0., 0., 0., 0., 0., 0., 0.],
  1890. [ 0., 0., 0., 0., 0., 0., 0., 0.],
  1891. [ 0., 0., 0., 0., 0., 0., 0., 0.]])
  1892. >>> y.shape = (3, 6)
  1893. Traceback (most recent call last):
  1894. File "<stdin>", line 1, in <module>
  1895. ValueError: total size of new array must be unchanged
  1896. >>> np.zeros((4,2))[::2].shape = (-1,)
  1897. Traceback (most recent call last):
  1898. File "<stdin>", line 1, in <module>
  1899. AttributeError: Incompatible shape for in-place modification. Use
  1900. `.reshape()` to make a copy with the desired shape.
  1901. See Also
  1902. --------
  1903. numpy.reshape : similar function
  1904. ndarray.reshape : similar method
  1905. """))
  1906. add_newdoc('numpy.core.multiarray', 'ndarray', ('size',
  1907. """
  1908. Number of elements in the array.
  1909. Equal to ``np.prod(a.shape)``, i.e., the product of the array's
  1910. dimensions.
  1911. Notes
  1912. -----
  1913. `a.size` returns a standard arbitrary precision Python integer. This
  1914. may not be the case with other methods of obtaining the same value
  1915. (like the suggested ``np.prod(a.shape)``, which returns an instance
  1916. of ``np.int_``), and may be relevant if the value is used further in
  1917. calculations that may overflow a fixed size integer type.
  1918. Examples
  1919. --------
  1920. >>> x = np.zeros((3, 5, 2), dtype=np.complex128)
  1921. >>> x.size
  1922. 30
  1923. >>> np.prod(x.shape)
  1924. 30
  1925. """))
  1926. add_newdoc('numpy.core.multiarray', 'ndarray', ('strides',
  1927. """
  1928. Tuple of bytes to step in each dimension when traversing an array.
  1929. The byte offset of element ``(i[0], i[1], ..., i[n])`` in an array `a`
  1930. is::
  1931. offset = sum(np.array(i) * a.strides)
  1932. A more detailed explanation of strides can be found in the
  1933. "ndarray.rst" file in the NumPy reference guide.
  1934. Notes
  1935. -----
  1936. Imagine an array of 32-bit integers (each 4 bytes)::
  1937. x = np.array([[0, 1, 2, 3, 4],
  1938. [5, 6, 7, 8, 9]], dtype=np.int32)
  1939. This array is stored in memory as 40 bytes, one after the other
  1940. (known as a contiguous block of memory). The strides of an array tell
  1941. us how many bytes we have to skip in memory to move to the next position
  1942. along a certain axis. For example, we have to skip 4 bytes (1 value) to
  1943. move to the next column, but 20 bytes (5 values) to get to the same
  1944. position in the next row. As such, the strides for the array `x` will be
  1945. ``(20, 4)``.
  1946. See Also
  1947. --------
  1948. numpy.lib.stride_tricks.as_strided
  1949. Examples
  1950. --------
  1951. >>> y = np.reshape(np.arange(2*3*4), (2,3,4))
  1952. >>> y
  1953. array([[[ 0, 1, 2, 3],
  1954. [ 4, 5, 6, 7],
  1955. [ 8, 9, 10, 11]],
  1956. [[12, 13, 14, 15],
  1957. [16, 17, 18, 19],
  1958. [20, 21, 22, 23]]])
  1959. >>> y.strides
  1960. (48, 16, 4)
  1961. >>> y[1,1,1]
  1962. 17
  1963. >>> offset=sum(y.strides * np.array((1,1,1)))
  1964. >>> offset/y.itemsize
  1965. 17
  1966. >>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0)
  1967. >>> x.strides
  1968. (32, 4, 224, 1344)
  1969. >>> i = np.array([3,5,2,2])
  1970. >>> offset = sum(i * x.strides)
  1971. >>> x[3,5,2,2]
  1972. 813
  1973. >>> offset / x.itemsize
  1974. 813
  1975. """))
  1976. add_newdoc('numpy.core.multiarray', 'ndarray', ('T',
  1977. """
  1978. The transposed array.
  1979. Same as ``self.transpose()``.
  1980. Examples
  1981. --------
  1982. >>> x = np.array([[1.,2.],[3.,4.]])
  1983. >>> x
  1984. array([[ 1., 2.],
  1985. [ 3., 4.]])
  1986. >>> x.T
  1987. array([[ 1., 3.],
  1988. [ 2., 4.]])
  1989. >>> x = np.array([1.,2.,3.,4.])
  1990. >>> x
  1991. array([ 1., 2., 3., 4.])
  1992. >>> x.T
  1993. array([ 1., 2., 3., 4.])
  1994. See Also
  1995. --------
  1996. transpose
  1997. """))
  1998. ##############################################################################
  1999. #
  2000. # ndarray methods
  2001. #
  2002. ##############################################################################
  2003. add_newdoc('numpy.core.multiarray', 'ndarray', ('__array__',
  2004. """ a.__array__([dtype], /) -> reference if type unchanged, copy otherwise.
  2005. Returns either a new reference to self if dtype is not given or a new array
  2006. of provided data type if dtype is different from the current dtype of the
  2007. array.
  2008. """))
  2009. add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_prepare__',
  2010. """a.__array_prepare__(obj) -> Object of same type as ndarray object obj.
  2011. """))
  2012. add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_wrap__',
  2013. """a.__array_wrap__(obj) -> Object of same type as ndarray object a.
  2014. """))
  2015. add_newdoc('numpy.core.multiarray', 'ndarray', ('__copy__',
  2016. """a.__copy__()
  2017. Used if :func:`copy.copy` is called on an array. Returns a copy of the array.
  2018. Equivalent to ``a.copy(order='K')``.
  2019. """))
  2020. add_newdoc('numpy.core.multiarray', 'ndarray', ('__deepcopy__',
  2021. """a.__deepcopy__(memo, /) -> Deep copy of array.
  2022. Used if :func:`copy.deepcopy` is called on an array.
  2023. """))
  2024. add_newdoc('numpy.core.multiarray', 'ndarray', ('__reduce__',
  2025. """a.__reduce__()
  2026. For pickling.
  2027. """))
  2028. add_newdoc('numpy.core.multiarray', 'ndarray', ('__setstate__',
  2029. """a.__setstate__(state, /)
  2030. For unpickling.
  2031. The `state` argument must be a sequence that contains the following
  2032. elements:
  2033. Parameters
  2034. ----------
  2035. version : int
  2036. optional pickle version. If omitted defaults to 0.
  2037. shape : tuple
  2038. dtype : data-type
  2039. isFortran : bool
  2040. rawdata : string or list
  2041. a binary string with the data (or a list if 'a' is an object array)
  2042. """))
  2043. add_newdoc('numpy.core.multiarray', 'ndarray', ('all',
  2044. """
  2045. a.all(axis=None, out=None, keepdims=False, *, where=True)
  2046. Returns True if all elements evaluate to True.
  2047. Refer to `numpy.all` for full documentation.
  2048. See Also
  2049. --------
  2050. numpy.all : equivalent function
  2051. """))
  2052. add_newdoc('numpy.core.multiarray', 'ndarray', ('any',
  2053. """
  2054. a.any(axis=None, out=None, keepdims=False, *, where=True)
  2055. Returns True if any of the elements of `a` evaluate to True.
  2056. Refer to `numpy.any` for full documentation.
  2057. See Also
  2058. --------
  2059. numpy.any : equivalent function
  2060. """))
  2061. add_newdoc('numpy.core.multiarray', 'ndarray', ('argmax',
  2062. """
  2063. a.argmax(axis=None, out=None)
  2064. Return indices of the maximum values along the given axis.
  2065. Refer to `numpy.argmax` for full documentation.
  2066. See Also
  2067. --------
  2068. numpy.argmax : equivalent function
  2069. """))
  2070. add_newdoc('numpy.core.multiarray', 'ndarray', ('argmin',
  2071. """
  2072. a.argmin(axis=None, out=None)
  2073. Return indices of the minimum values along the given axis.
  2074. Refer to `numpy.argmin` for detailed documentation.
  2075. See Also
  2076. --------
  2077. numpy.argmin : equivalent function
  2078. """))
  2079. add_newdoc('numpy.core.multiarray', 'ndarray', ('argsort',
  2080. """
  2081. a.argsort(axis=-1, kind=None, order=None)
  2082. Returns the indices that would sort this array.
  2083. Refer to `numpy.argsort` for full documentation.
  2084. See Also
  2085. --------
  2086. numpy.argsort : equivalent function
  2087. """))
  2088. add_newdoc('numpy.core.multiarray', 'ndarray', ('argpartition',
  2089. """
  2090. a.argpartition(kth, axis=-1, kind='introselect', order=None)
  2091. Returns the indices that would partition this array.
  2092. Refer to `numpy.argpartition` for full documentation.
  2093. .. versionadded:: 1.8.0
  2094. See Also
  2095. --------
  2096. numpy.argpartition : equivalent function
  2097. """))
  2098. add_newdoc('numpy.core.multiarray', 'ndarray', ('astype',
  2099. """
  2100. a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
  2101. Copy of the array, cast to a specified type.
  2102. Parameters
  2103. ----------
  2104. dtype : str or dtype
  2105. Typecode or data-type to which the array is cast.
  2106. order : {'C', 'F', 'A', 'K'}, optional
  2107. Controls the memory layout order of the result.
  2108. 'C' means C order, 'F' means Fortran order, 'A'
  2109. means 'F' order if all the arrays are Fortran contiguous,
  2110. 'C' order otherwise, and 'K' means as close to the
  2111. order the array elements appear in memory as possible.
  2112. Default is 'K'.
  2113. casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
  2114. Controls what kind of data casting may occur. Defaults to 'unsafe'
  2115. for backwards compatibility.
  2116. * 'no' means the data types should not be cast at all.
  2117. * 'equiv' means only byte-order changes are allowed.
  2118. * 'safe' means only casts which can preserve values are allowed.
  2119. * 'same_kind' means only safe casts or casts within a kind,
  2120. like float64 to float32, are allowed.
  2121. * 'unsafe' means any data conversions may be done.
  2122. subok : bool, optional
  2123. If True, then sub-classes will be passed-through (default), otherwise
  2124. the returned array will be forced to be a base-class array.
  2125. copy : bool, optional
  2126. By default, astype always returns a newly allocated array. If this
  2127. is set to false, and the `dtype`, `order`, and `subok`
  2128. requirements are satisfied, the input array is returned instead
  2129. of a copy.
  2130. Returns
  2131. -------
  2132. arr_t : ndarray
  2133. Unless `copy` is False and the other conditions for returning the input
  2134. array are satisfied (see description for `copy` input parameter), `arr_t`
  2135. is a new array of the same shape as the input array, with dtype, order
  2136. given by `dtype`, `order`.
  2137. Notes
  2138. -----
  2139. .. versionchanged:: 1.17.0
  2140. Casting between a simple data type and a structured one is possible only
  2141. for "unsafe" casting. Casting to multiple fields is allowed, but
  2142. casting from multiple fields is not.
  2143. .. versionchanged:: 1.9.0
  2144. Casting from numeric to string types in 'safe' casting mode requires
  2145. that the string dtype length is long enough to store the max
  2146. integer/float value converted.
  2147. Raises
  2148. ------
  2149. ComplexWarning
  2150. When casting from complex to float or int. To avoid this,
  2151. one should use ``a.real.astype(t)``.
  2152. Examples
  2153. --------
  2154. >>> x = np.array([1, 2, 2.5])
  2155. >>> x
  2156. array([1. , 2. , 2.5])
  2157. >>> x.astype(int)
  2158. array([1, 2, 2])
  2159. """))
  2160. add_newdoc('numpy.core.multiarray', 'ndarray', ('byteswap',
  2161. """
  2162. a.byteswap(inplace=False)
  2163. Swap the bytes of the array elements
  2164. Toggle between low-endian and big-endian data representation by
  2165. returning a byteswapped array, optionally swapped in-place.
  2166. Arrays of byte-strings are not swapped. The real and imaginary
  2167. parts of a complex number are swapped individually.
  2168. Parameters
  2169. ----------
  2170. inplace : bool, optional
  2171. If ``True``, swap bytes in-place, default is ``False``.
  2172. Returns
  2173. -------
  2174. out : ndarray
  2175. The byteswapped array. If `inplace` is ``True``, this is
  2176. a view to self.
  2177. Examples
  2178. --------
  2179. >>> A = np.array([1, 256, 8755], dtype=np.int16)
  2180. >>> list(map(hex, A))
  2181. ['0x1', '0x100', '0x2233']
  2182. >>> A.byteswap(inplace=True)
  2183. array([ 256, 1, 13090], dtype=int16)
  2184. >>> list(map(hex, A))
  2185. ['0x100', '0x1', '0x3322']
  2186. Arrays of byte-strings are not swapped
  2187. >>> A = np.array([b'ceg', b'fac'])
  2188. >>> A.byteswap()
  2189. array([b'ceg', b'fac'], dtype='|S3')
  2190. ``A.newbyteorder().byteswap()`` produces an array with the same values
  2191. but different representation in memory
  2192. >>> A = np.array([1, 2, 3])
  2193. >>> A.view(np.uint8)
  2194. array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0,
  2195. 0, 0], dtype=uint8)
  2196. >>> A.newbyteorder().byteswap(inplace=True)
  2197. array([1, 2, 3])
  2198. >>> A.view(np.uint8)
  2199. array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,
  2200. 0, 3], dtype=uint8)
  2201. """))
  2202. add_newdoc('numpy.core.multiarray', 'ndarray', ('choose',
  2203. """
  2204. a.choose(choices, out=None, mode='raise')
  2205. Use an index array to construct a new array from a set of choices.
  2206. Refer to `numpy.choose` for full documentation.
  2207. See Also
  2208. --------
  2209. numpy.choose : equivalent function
  2210. """))
  2211. add_newdoc('numpy.core.multiarray', 'ndarray', ('clip',
  2212. """
  2213. a.clip(min=None, max=None, out=None, **kwargs)
  2214. Return an array whose values are limited to ``[min, max]``.
  2215. One of max or min must be given.
  2216. Refer to `numpy.clip` for full documentation.
  2217. See Also
  2218. --------
  2219. numpy.clip : equivalent function
  2220. """))
  2221. add_newdoc('numpy.core.multiarray', 'ndarray', ('compress',
  2222. """
  2223. a.compress(condition, axis=None, out=None)
  2224. Return selected slices of this array along given axis.
  2225. Refer to `numpy.compress` for full documentation.
  2226. See Also
  2227. --------
  2228. numpy.compress : equivalent function
  2229. """))
  2230. add_newdoc('numpy.core.multiarray', 'ndarray', ('conj',
  2231. """
  2232. a.conj()
  2233. Complex-conjugate all elements.
  2234. Refer to `numpy.conjugate` for full documentation.
  2235. See Also
  2236. --------
  2237. numpy.conjugate : equivalent function
  2238. """))
  2239. add_newdoc('numpy.core.multiarray', 'ndarray', ('conjugate',
  2240. """
  2241. a.conjugate()
  2242. Return the complex conjugate, element-wise.
  2243. Refer to `numpy.conjugate` for full documentation.
  2244. See Also
  2245. --------
  2246. numpy.conjugate : equivalent function
  2247. """))
  2248. add_newdoc('numpy.core.multiarray', 'ndarray', ('copy',
  2249. """
  2250. a.copy(order='C')
  2251. Return a copy of the array.
  2252. Parameters
  2253. ----------
  2254. order : {'C', 'F', 'A', 'K'}, optional
  2255. Controls the memory layout of the copy. 'C' means C-order,
  2256. 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
  2257. 'C' otherwise. 'K' means match the layout of `a` as closely
  2258. as possible. (Note that this function and :func:`numpy.copy` are very
  2259. similar, but have different default values for their order=
  2260. arguments.)
  2261. See also
  2262. --------
  2263. numpy.copy
  2264. numpy.copyto
  2265. Examples
  2266. --------
  2267. >>> x = np.array([[1,2,3],[4,5,6]], order='F')
  2268. >>> y = x.copy()
  2269. >>> x.fill(0)
  2270. >>> x
  2271. array([[0, 0, 0],
  2272. [0, 0, 0]])
  2273. >>> y
  2274. array([[1, 2, 3],
  2275. [4, 5, 6]])
  2276. >>> y.flags['C_CONTIGUOUS']
  2277. True
  2278. """))
  2279. add_newdoc('numpy.core.multiarray', 'ndarray', ('cumprod',
  2280. """
  2281. a.cumprod(axis=None, dtype=None, out=None)
  2282. Return the cumulative product of the elements along the given axis.
  2283. Refer to `numpy.cumprod` for full documentation.
  2284. See Also
  2285. --------
  2286. numpy.cumprod : equivalent function
  2287. """))
  2288. add_newdoc('numpy.core.multiarray', 'ndarray', ('cumsum',
  2289. """
  2290. a.cumsum(axis=None, dtype=None, out=None)
  2291. Return the cumulative sum of the elements along the given axis.
  2292. Refer to `numpy.cumsum` for full documentation.
  2293. See Also
  2294. --------
  2295. numpy.cumsum : equivalent function
  2296. """))
  2297. add_newdoc('numpy.core.multiarray', 'ndarray', ('diagonal',
  2298. """
  2299. a.diagonal(offset=0, axis1=0, axis2=1)
  2300. Return specified diagonals. In NumPy 1.9 the returned array is a
  2301. read-only view instead of a copy as in previous NumPy versions. In
  2302. a future version the read-only restriction will be removed.
  2303. Refer to :func:`numpy.diagonal` for full documentation.
  2304. See Also
  2305. --------
  2306. numpy.diagonal : equivalent function
  2307. """))
  2308. add_newdoc('numpy.core.multiarray', 'ndarray', ('dot',
  2309. """
  2310. a.dot(b, out=None)
  2311. Dot product of two arrays.
  2312. Refer to `numpy.dot` for full documentation.
  2313. See Also
  2314. --------
  2315. numpy.dot : equivalent function
  2316. Examples
  2317. --------
  2318. >>> a = np.eye(2)
  2319. >>> b = np.ones((2, 2)) * 2
  2320. >>> a.dot(b)
  2321. array([[2., 2.],
  2322. [2., 2.]])
  2323. This array method can be conveniently chained:
  2324. >>> a.dot(b).dot(b)
  2325. array([[8., 8.],
  2326. [8., 8.]])
  2327. """))
  2328. add_newdoc('numpy.core.multiarray', 'ndarray', ('dump',
  2329. """a.dump(file)
  2330. Dump a pickle of the array to the specified file.
  2331. The array can be read back with pickle.load or numpy.load.
  2332. Parameters
  2333. ----------
  2334. file : str or Path
  2335. A string naming the dump file.
  2336. .. versionchanged:: 1.17.0
  2337. `pathlib.Path` objects are now accepted.
  2338. """))
  2339. add_newdoc('numpy.core.multiarray', 'ndarray', ('dumps',
  2340. """
  2341. a.dumps()
  2342. Returns the pickle of the array as a string.
  2343. pickle.loads or numpy.loads will convert the string back to an array.
  2344. Parameters
  2345. ----------
  2346. None
  2347. """))
  2348. add_newdoc('numpy.core.multiarray', 'ndarray', ('fill',
  2349. """
  2350. a.fill(value)
  2351. Fill the array with a scalar value.
  2352. Parameters
  2353. ----------
  2354. value : scalar
  2355. All elements of `a` will be assigned this value.
  2356. Examples
  2357. --------
  2358. >>> a = np.array([1, 2])
  2359. >>> a.fill(0)
  2360. >>> a
  2361. array([0, 0])
  2362. >>> a = np.empty(2)
  2363. >>> a.fill(1)
  2364. >>> a
  2365. array([1., 1.])
  2366. """))
  2367. add_newdoc('numpy.core.multiarray', 'ndarray', ('flatten',
  2368. """
  2369. a.flatten(order='C')
  2370. Return a copy of the array collapsed into one dimension.
  2371. Parameters
  2372. ----------
  2373. order : {'C', 'F', 'A', 'K'}, optional
  2374. 'C' means to flatten in row-major (C-style) order.
  2375. 'F' means to flatten in column-major (Fortran-
  2376. style) order. 'A' means to flatten in column-major
  2377. order if `a` is Fortran *contiguous* in memory,
  2378. row-major order otherwise. 'K' means to flatten
  2379. `a` in the order the elements occur in memory.
  2380. The default is 'C'.
  2381. Returns
  2382. -------
  2383. y : ndarray
  2384. A copy of the input array, flattened to one dimension.
  2385. See Also
  2386. --------
  2387. ravel : Return a flattened array.
  2388. flat : A 1-D flat iterator over the array.
  2389. Examples
  2390. --------
  2391. >>> a = np.array([[1,2], [3,4]])
  2392. >>> a.flatten()
  2393. array([1, 2, 3, 4])
  2394. >>> a.flatten('F')
  2395. array([1, 3, 2, 4])
  2396. """))
  2397. add_newdoc('numpy.core.multiarray', 'ndarray', ('getfield',
  2398. """
  2399. a.getfield(dtype, offset=0)
  2400. Returns a field of the given array as a certain type.
  2401. A field is a view of the array data with a given data-type. The values in
  2402. the view are determined by the given type and the offset into the current
  2403. array in bytes. The offset needs to be such that the view dtype fits in the
  2404. array dtype; for example an array of dtype complex128 has 16-byte elements.
  2405. If taking a view with a 32-bit integer (4 bytes), the offset needs to be
  2406. between 0 and 12 bytes.
  2407. Parameters
  2408. ----------
  2409. dtype : str or dtype
  2410. The data type of the view. The dtype size of the view can not be larger
  2411. than that of the array itself.
  2412. offset : int
  2413. Number of bytes to skip before beginning the element view.
  2414. Examples
  2415. --------
  2416. >>> x = np.diag([1.+1.j]*2)
  2417. >>> x[1, 1] = 2 + 4.j
  2418. >>> x
  2419. array([[1.+1.j, 0.+0.j],
  2420. [0.+0.j, 2.+4.j]])
  2421. >>> x.getfield(np.float64)
  2422. array([[1., 0.],
  2423. [0., 2.]])
  2424. By choosing an offset of 8 bytes we can select the complex part of the
  2425. array for our view:
  2426. >>> x.getfield(np.float64, offset=8)
  2427. array([[1., 0.],
  2428. [0., 4.]])
  2429. """))
  2430. add_newdoc('numpy.core.multiarray', 'ndarray', ('item',
  2431. """
  2432. a.item(*args)
  2433. Copy an element of an array to a standard Python scalar and return it.
  2434. Parameters
  2435. ----------
  2436. \\*args : Arguments (variable number and type)
  2437. * none: in this case, the method only works for arrays
  2438. with one element (`a.size == 1`), which element is
  2439. copied into a standard Python scalar object and returned.
  2440. * int_type: this argument is interpreted as a flat index into
  2441. the array, specifying which element to copy and return.
  2442. * tuple of int_types: functions as does a single int_type argument,
  2443. except that the argument is interpreted as an nd-index into the
  2444. array.
  2445. Returns
  2446. -------
  2447. z : Standard Python scalar object
  2448. A copy of the specified element of the array as a suitable
  2449. Python scalar
  2450. Notes
  2451. -----
  2452. When the data type of `a` is longdouble or clongdouble, item() returns
  2453. a scalar array object because there is no available Python scalar that
  2454. would not lose information. Void arrays return a buffer object for item(),
  2455. unless fields are defined, in which case a tuple is returned.
  2456. `item` is very similar to a[args], except, instead of an array scalar,
  2457. a standard Python scalar is returned. This can be useful for speeding up
  2458. access to elements of the array and doing arithmetic on elements of the
  2459. array using Python's optimized math.
  2460. Examples
  2461. --------
  2462. >>> np.random.seed(123)
  2463. >>> x = np.random.randint(9, size=(3, 3))
  2464. >>> x
  2465. array([[2, 2, 6],
  2466. [1, 3, 6],
  2467. [1, 0, 1]])
  2468. >>> x.item(3)
  2469. 1
  2470. >>> x.item(7)
  2471. 0
  2472. >>> x.item((0, 1))
  2473. 2
  2474. >>> x.item((2, 2))
  2475. 1
  2476. """))
  2477. add_newdoc('numpy.core.multiarray', 'ndarray', ('itemset',
  2478. """
  2479. a.itemset(*args)
  2480. Insert scalar into an array (scalar is cast to array's dtype, if possible)
  2481. There must be at least 1 argument, and define the last argument
  2482. as *item*. Then, ``a.itemset(*args)`` is equivalent to but faster
  2483. than ``a[args] = item``. The item should be a scalar value and `args`
  2484. must select a single item in the array `a`.
  2485. Parameters
  2486. ----------
  2487. \\*args : Arguments
  2488. If one argument: a scalar, only used in case `a` is of size 1.
  2489. If two arguments: the last argument is the value to be set
  2490. and must be a scalar, the first argument specifies a single array
  2491. element location. It is either an int or a tuple.
  2492. Notes
  2493. -----
  2494. Compared to indexing syntax, `itemset` provides some speed increase
  2495. for placing a scalar into a particular location in an `ndarray`,
  2496. if you must do this. However, generally this is discouraged:
  2497. among other problems, it complicates the appearance of the code.
  2498. Also, when using `itemset` (and `item`) inside a loop, be sure
  2499. to assign the methods to a local variable to avoid the attribute
  2500. look-up at each loop iteration.
  2501. Examples
  2502. --------
  2503. >>> np.random.seed(123)
  2504. >>> x = np.random.randint(9, size=(3, 3))
  2505. >>> x
  2506. array([[2, 2, 6],
  2507. [1, 3, 6],
  2508. [1, 0, 1]])
  2509. >>> x.itemset(4, 0)
  2510. >>> x.itemset((2, 2), 9)
  2511. >>> x
  2512. array([[2, 2, 6],
  2513. [1, 0, 6],
  2514. [1, 0, 9]])
  2515. """))
  2516. add_newdoc('numpy.core.multiarray', 'ndarray', ('max',
  2517. """
  2518. a.max(axis=None, out=None, keepdims=False, initial=<no value>, where=True)
  2519. Return the maximum along a given axis.
  2520. Refer to `numpy.amax` for full documentation.
  2521. See Also
  2522. --------
  2523. numpy.amax : equivalent function
  2524. """))
  2525. add_newdoc('numpy.core.multiarray', 'ndarray', ('mean',
  2526. """
  2527. a.mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True)
  2528. Returns the average of the array elements along given axis.
  2529. Refer to `numpy.mean` for full documentation.
  2530. See Also
  2531. --------
  2532. numpy.mean : equivalent function
  2533. """))
  2534. add_newdoc('numpy.core.multiarray', 'ndarray', ('min',
  2535. """
  2536. a.min(axis=None, out=None, keepdims=False, initial=<no value>, where=True)
  2537. Return the minimum along a given axis.
  2538. Refer to `numpy.amin` for full documentation.
  2539. See Also
  2540. --------
  2541. numpy.amin : equivalent function
  2542. """))
  2543. add_newdoc('numpy.core.multiarray', 'ndarray', ('newbyteorder',
  2544. """
  2545. arr.newbyteorder(new_order='S', /)
  2546. Return the array with the same data viewed with a different byte order.
  2547. Equivalent to::
  2548. arr.view(arr.dtype.newbytorder(new_order))
  2549. Changes are also made in all fields and sub-arrays of the array data
  2550. type.
  2551. Parameters
  2552. ----------
  2553. new_order : string, optional
  2554. Byte order to force; a value from the byte order specifications
  2555. below. `new_order` codes can be any of:
  2556. * 'S' - swap dtype from current to opposite endian
  2557. * {'<', 'little'} - little endian
  2558. * {'>', 'big'} - big endian
  2559. * '=' - native order, equivalent to `sys.byteorder`
  2560. * {'|', 'I'} - ignore (no change to byte order)
  2561. The default value ('S') results in swapping the current
  2562. byte order.
  2563. Returns
  2564. -------
  2565. new_arr : array
  2566. New array object with the dtype reflecting given change to the
  2567. byte order.
  2568. """))
  2569. add_newdoc('numpy.core.multiarray', 'ndarray', ('nonzero',
  2570. """
  2571. a.nonzero()
  2572. Return the indices of the elements that are non-zero.
  2573. Refer to `numpy.nonzero` for full documentation.
  2574. See Also
  2575. --------
  2576. numpy.nonzero : equivalent function
  2577. """))
  2578. add_newdoc('numpy.core.multiarray', 'ndarray', ('prod',
  2579. """
  2580. a.prod(axis=None, dtype=None, out=None, keepdims=False, initial=1, where=True)
  2581. Return the product of the array elements over the given axis
  2582. Refer to `numpy.prod` for full documentation.
  2583. See Also
  2584. --------
  2585. numpy.prod : equivalent function
  2586. """))
  2587. add_newdoc('numpy.core.multiarray', 'ndarray', ('ptp',
  2588. """
  2589. a.ptp(axis=None, out=None, keepdims=False)
  2590. Peak to peak (maximum - minimum) value along a given axis.
  2591. Refer to `numpy.ptp` for full documentation.
  2592. See Also
  2593. --------
  2594. numpy.ptp : equivalent function
  2595. """))
  2596. add_newdoc('numpy.core.multiarray', 'ndarray', ('put',
  2597. """
  2598. a.put(indices, values, mode='raise')
  2599. Set ``a.flat[n] = values[n]`` for all `n` in indices.
  2600. Refer to `numpy.put` for full documentation.
  2601. See Also
  2602. --------
  2603. numpy.put : equivalent function
  2604. """))
  2605. add_newdoc('numpy.core.multiarray', 'ndarray', ('ravel',
  2606. """
  2607. a.ravel([order])
  2608. Return a flattened array.
  2609. Refer to `numpy.ravel` for full documentation.
  2610. See Also
  2611. --------
  2612. numpy.ravel : equivalent function
  2613. ndarray.flat : a flat iterator on the array.
  2614. """))
  2615. add_newdoc('numpy.core.multiarray', 'ndarray', ('repeat',
  2616. """
  2617. a.repeat(repeats, axis=None)
  2618. Repeat elements of an array.
  2619. Refer to `numpy.repeat` for full documentation.
  2620. See Also
  2621. --------
  2622. numpy.repeat : equivalent function
  2623. """))
  2624. add_newdoc('numpy.core.multiarray', 'ndarray', ('reshape',
  2625. """
  2626. a.reshape(shape, order='C')
  2627. Returns an array containing the same data with a new shape.
  2628. Refer to `numpy.reshape` for full documentation.
  2629. See Also
  2630. --------
  2631. numpy.reshape : equivalent function
  2632. Notes
  2633. -----
  2634. Unlike the free function `numpy.reshape`, this method on `ndarray` allows
  2635. the elements of the shape parameter to be passed in as separate arguments.
  2636. For example, ``a.reshape(10, 11)`` is equivalent to
  2637. ``a.reshape((10, 11))``.
  2638. """))
  2639. add_newdoc('numpy.core.multiarray', 'ndarray', ('resize',
  2640. """
  2641. a.resize(new_shape, refcheck=True)
  2642. Change shape and size of array in-place.
  2643. Parameters
  2644. ----------
  2645. new_shape : tuple of ints, or `n` ints
  2646. Shape of resized array.
  2647. refcheck : bool, optional
  2648. If False, reference count will not be checked. Default is True.
  2649. Returns
  2650. -------
  2651. None
  2652. Raises
  2653. ------
  2654. ValueError
  2655. If `a` does not own its own data or references or views to it exist,
  2656. and the data memory must be changed.
  2657. PyPy only: will always raise if the data memory must be changed, since
  2658. there is no reliable way to determine if references or views to it
  2659. exist.
  2660. SystemError
  2661. If the `order` keyword argument is specified. This behaviour is a
  2662. bug in NumPy.
  2663. See Also
  2664. --------
  2665. resize : Return a new array with the specified shape.
  2666. Notes
  2667. -----
  2668. This reallocates space for the data area if necessary.
  2669. Only contiguous arrays (data elements consecutive in memory) can be
  2670. resized.
  2671. The purpose of the reference count check is to make sure you
  2672. do not use this array as a buffer for another Python object and then
  2673. reallocate the memory. However, reference counts can increase in
  2674. other ways so if you are sure that you have not shared the memory
  2675. for this array with another Python object, then you may safely set
  2676. `refcheck` to False.
  2677. Examples
  2678. --------
  2679. Shrinking an array: array is flattened (in the order that the data are
  2680. stored in memory), resized, and reshaped:
  2681. >>> a = np.array([[0, 1], [2, 3]], order='C')
  2682. >>> a.resize((2, 1))
  2683. >>> a
  2684. array([[0],
  2685. [1]])
  2686. >>> a = np.array([[0, 1], [2, 3]], order='F')
  2687. >>> a.resize((2, 1))
  2688. >>> a
  2689. array([[0],
  2690. [2]])
  2691. Enlarging an array: as above, but missing entries are filled with zeros:
  2692. >>> b = np.array([[0, 1], [2, 3]])
  2693. >>> b.resize(2, 3) # new_shape parameter doesn't have to be a tuple
  2694. >>> b
  2695. array([[0, 1, 2],
  2696. [3, 0, 0]])
  2697. Referencing an array prevents resizing...
  2698. >>> c = a
  2699. >>> a.resize((1, 1))
  2700. Traceback (most recent call last):
  2701. ...
  2702. ValueError: cannot resize an array that references or is referenced ...
  2703. Unless `refcheck` is False:
  2704. >>> a.resize((1, 1), refcheck=False)
  2705. >>> a
  2706. array([[0]])
  2707. >>> c
  2708. array([[0]])
  2709. """))
  2710. add_newdoc('numpy.core.multiarray', 'ndarray', ('round',
  2711. """
  2712. a.round(decimals=0, out=None)
  2713. Return `a` with each element rounded to the given number of decimals.
  2714. Refer to `numpy.around` for full documentation.
  2715. See Also
  2716. --------
  2717. numpy.around : equivalent function
  2718. """))
  2719. add_newdoc('numpy.core.multiarray', 'ndarray', ('searchsorted',
  2720. """
  2721. a.searchsorted(v, side='left', sorter=None)
  2722. Find indices where elements of v should be inserted in a to maintain order.
  2723. For full documentation, see `numpy.searchsorted`
  2724. See Also
  2725. --------
  2726. numpy.searchsorted : equivalent function
  2727. """))
  2728. add_newdoc('numpy.core.multiarray', 'ndarray', ('setfield',
  2729. """
  2730. a.setfield(val, dtype, offset=0)
  2731. Put a value into a specified place in a field defined by a data-type.
  2732. Place `val` into `a`'s field defined by `dtype` and beginning `offset`
  2733. bytes into the field.
  2734. Parameters
  2735. ----------
  2736. val : object
  2737. Value to be placed in field.
  2738. dtype : dtype object
  2739. Data-type of the field in which to place `val`.
  2740. offset : int, optional
  2741. The number of bytes into the field at which to place `val`.
  2742. Returns
  2743. -------
  2744. None
  2745. See Also
  2746. --------
  2747. getfield
  2748. Examples
  2749. --------
  2750. >>> x = np.eye(3)
  2751. >>> x.getfield(np.float64)
  2752. array([[1., 0., 0.],
  2753. [0., 1., 0.],
  2754. [0., 0., 1.]])
  2755. >>> x.setfield(3, np.int32)
  2756. >>> x.getfield(np.int32)
  2757. array([[3, 3, 3],
  2758. [3, 3, 3],
  2759. [3, 3, 3]], dtype=int32)
  2760. >>> x
  2761. array([[1.0e+000, 1.5e-323, 1.5e-323],
  2762. [1.5e-323, 1.0e+000, 1.5e-323],
  2763. [1.5e-323, 1.5e-323, 1.0e+000]])
  2764. >>> x.setfield(np.eye(3), np.int32)
  2765. >>> x
  2766. array([[1., 0., 0.],
  2767. [0., 1., 0.],
  2768. [0., 0., 1.]])
  2769. """))
  2770. add_newdoc('numpy.core.multiarray', 'ndarray', ('setflags',
  2771. """
  2772. a.setflags(write=None, align=None, uic=None)
  2773. Set array flags WRITEABLE, ALIGNED, (WRITEBACKIFCOPY and UPDATEIFCOPY),
  2774. respectively.
  2775. These Boolean-valued flags affect how numpy interprets the memory
  2776. area used by `a` (see Notes below). The ALIGNED flag can only
  2777. be set to True if the data is actually aligned according to the type.
  2778. The WRITEBACKIFCOPY and (deprecated) UPDATEIFCOPY flags can never be set
  2779. to True. The flag WRITEABLE can only be set to True if the array owns its
  2780. own memory, or the ultimate owner of the memory exposes a writeable buffer
  2781. interface, or is a string. (The exception for string is made so that
  2782. unpickling can be done without copying memory.)
  2783. Parameters
  2784. ----------
  2785. write : bool, optional
  2786. Describes whether or not `a` can be written to.
  2787. align : bool, optional
  2788. Describes whether or not `a` is aligned properly for its type.
  2789. uic : bool, optional
  2790. Describes whether or not `a` is a copy of another "base" array.
  2791. Notes
  2792. -----
  2793. Array flags provide information about how the memory area used
  2794. for the array is to be interpreted. There are 7 Boolean flags
  2795. in use, only four of which can be changed by the user:
  2796. WRITEBACKIFCOPY, UPDATEIFCOPY, WRITEABLE, and ALIGNED.
  2797. WRITEABLE (W) the data area can be written to;
  2798. ALIGNED (A) the data and strides are aligned appropriately for the hardware
  2799. (as determined by the compiler);
  2800. UPDATEIFCOPY (U) (deprecated), replaced by WRITEBACKIFCOPY;
  2801. WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced
  2802. by .base). When the C-API function PyArray_ResolveWritebackIfCopy is
  2803. called, the base array will be updated with the contents of this array.
  2804. All flags can be accessed using the single (upper case) letter as well
  2805. as the full name.
  2806. Examples
  2807. --------
  2808. >>> y = np.array([[3, 1, 7],
  2809. ... [2, 0, 0],
  2810. ... [8, 5, 9]])
  2811. >>> y
  2812. array([[3, 1, 7],
  2813. [2, 0, 0],
  2814. [8, 5, 9]])
  2815. >>> y.flags
  2816. C_CONTIGUOUS : True
  2817. F_CONTIGUOUS : False
  2818. OWNDATA : True
  2819. WRITEABLE : True
  2820. ALIGNED : True
  2821. WRITEBACKIFCOPY : False
  2822. UPDATEIFCOPY : False
  2823. >>> y.setflags(write=0, align=0)
  2824. >>> y.flags
  2825. C_CONTIGUOUS : True
  2826. F_CONTIGUOUS : False
  2827. OWNDATA : True
  2828. WRITEABLE : False
  2829. ALIGNED : False
  2830. WRITEBACKIFCOPY : False
  2831. UPDATEIFCOPY : False
  2832. >>> y.setflags(uic=1)
  2833. Traceback (most recent call last):
  2834. File "<stdin>", line 1, in <module>
  2835. ValueError: cannot set WRITEBACKIFCOPY flag to True
  2836. """))
  2837. add_newdoc('numpy.core.multiarray', 'ndarray', ('sort',
  2838. """
  2839. a.sort(axis=-1, kind=None, order=None)
  2840. Sort an array in-place. Refer to `numpy.sort` for full documentation.
  2841. Parameters
  2842. ----------
  2843. axis : int, optional
  2844. Axis along which to sort. Default is -1, which means sort along the
  2845. last axis.
  2846. kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
  2847. Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
  2848. and 'mergesort' use timsort under the covers and, in general, the
  2849. actual implementation will vary with datatype. The 'mergesort' option
  2850. is retained for backwards compatibility.
  2851. .. versionchanged:: 1.15.0.
  2852. The 'stable' option was added.
  2853. order : str or list of str, optional
  2854. When `a` is an array with fields defined, this argument specifies
  2855. which fields to compare first, second, etc. A single field can
  2856. be specified as a string, and not all fields need be specified,
  2857. but unspecified fields will still be used, in the order in which
  2858. they come up in the dtype, to break ties.
  2859. See Also
  2860. --------
  2861. numpy.sort : Return a sorted copy of an array.
  2862. numpy.argsort : Indirect sort.
  2863. numpy.lexsort : Indirect stable sort on multiple keys.
  2864. numpy.searchsorted : Find elements in sorted array.
  2865. numpy.partition: Partial sort.
  2866. Notes
  2867. -----
  2868. See `numpy.sort` for notes on the different sorting algorithms.
  2869. Examples
  2870. --------
  2871. >>> a = np.array([[1,4], [3,1]])
  2872. >>> a.sort(axis=1)
  2873. >>> a
  2874. array([[1, 4],
  2875. [1, 3]])
  2876. >>> a.sort(axis=0)
  2877. >>> a
  2878. array([[1, 3],
  2879. [1, 4]])
  2880. Use the `order` keyword to specify a field to use when sorting a
  2881. structured array:
  2882. >>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)])
  2883. >>> a.sort(order='y')
  2884. >>> a
  2885. array([(b'c', 1), (b'a', 2)],
  2886. dtype=[('x', 'S1'), ('y', '<i8')])
  2887. """))
  2888. add_newdoc('numpy.core.multiarray', 'ndarray', ('partition',
  2889. """
  2890. a.partition(kth, axis=-1, kind='introselect', order=None)
  2891. Rearranges the elements in the array in such a way that the value of the
  2892. element in kth position is in the position it would be in a sorted array.
  2893. All elements smaller than the kth element are moved before this element and
  2894. all equal or greater are moved behind it. The ordering of the elements in
  2895. the two partitions is undefined.
  2896. .. versionadded:: 1.8.0
  2897. Parameters
  2898. ----------
  2899. kth : int or sequence of ints
  2900. Element index to partition by. The kth element value will be in its
  2901. final sorted position and all smaller elements will be moved before it
  2902. and all equal or greater elements behind it.
  2903. The order of all elements in the partitions is undefined.
  2904. If provided with a sequence of kth it will partition all elements
  2905. indexed by kth of them into their sorted position at once.
  2906. axis : int, optional
  2907. Axis along which to sort. Default is -1, which means sort along the
  2908. last axis.
  2909. kind : {'introselect'}, optional
  2910. Selection algorithm. Default is 'introselect'.
  2911. order : str or list of str, optional
  2912. When `a` is an array with fields defined, this argument specifies
  2913. which fields to compare first, second, etc. A single field can
  2914. be specified as a string, and not all fields need to be specified,
  2915. but unspecified fields will still be used, in the order in which
  2916. they come up in the dtype, to break ties.
  2917. See Also
  2918. --------
  2919. numpy.partition : Return a parititioned copy of an array.
  2920. argpartition : Indirect partition.
  2921. sort : Full sort.
  2922. Notes
  2923. -----
  2924. See ``np.partition`` for notes on the different algorithms.
  2925. Examples
  2926. --------
  2927. >>> a = np.array([3, 4, 2, 1])
  2928. >>> a.partition(3)
  2929. >>> a
  2930. array([2, 1, 3, 4])
  2931. >>> a.partition((1, 3))
  2932. >>> a
  2933. array([1, 2, 3, 4])
  2934. """))
  2935. add_newdoc('numpy.core.multiarray', 'ndarray', ('squeeze',
  2936. """
  2937. a.squeeze(axis=None)
  2938. Remove axes of length one from `a`.
  2939. Refer to `numpy.squeeze` for full documentation.
  2940. See Also
  2941. --------
  2942. numpy.squeeze : equivalent function
  2943. """))
  2944. add_newdoc('numpy.core.multiarray', 'ndarray', ('std',
  2945. """
  2946. a.std(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)
  2947. Returns the standard deviation of the array elements along given axis.
  2948. Refer to `numpy.std` for full documentation.
  2949. See Also
  2950. --------
  2951. numpy.std : equivalent function
  2952. """))
  2953. add_newdoc('numpy.core.multiarray', 'ndarray', ('sum',
  2954. """
  2955. a.sum(axis=None, dtype=None, out=None, keepdims=False, initial=0, where=True)
  2956. Return the sum of the array elements over the given axis.
  2957. Refer to `numpy.sum` for full documentation.
  2958. See Also
  2959. --------
  2960. numpy.sum : equivalent function
  2961. """))
  2962. add_newdoc('numpy.core.multiarray', 'ndarray', ('swapaxes',
  2963. """
  2964. a.swapaxes(axis1, axis2)
  2965. Return a view of the array with `axis1` and `axis2` interchanged.
  2966. Refer to `numpy.swapaxes` for full documentation.
  2967. See Also
  2968. --------
  2969. numpy.swapaxes : equivalent function
  2970. """))
  2971. add_newdoc('numpy.core.multiarray', 'ndarray', ('take',
  2972. """
  2973. a.take(indices, axis=None, out=None, mode='raise')
  2974. Return an array formed from the elements of `a` at the given indices.
  2975. Refer to `numpy.take` for full documentation.
  2976. See Also
  2977. --------
  2978. numpy.take : equivalent function
  2979. """))
  2980. add_newdoc('numpy.core.multiarray', 'ndarray', ('tofile',
  2981. """
  2982. a.tofile(fid, sep="", format="%s")
  2983. Write array to a file as text or binary (default).
  2984. Data is always written in 'C' order, independent of the order of `a`.
  2985. The data produced by this method can be recovered using the function
  2986. fromfile().
  2987. Parameters
  2988. ----------
  2989. fid : file or str or Path
  2990. An open file object, or a string containing a filename.
  2991. .. versionchanged:: 1.17.0
  2992. `pathlib.Path` objects are now accepted.
  2993. sep : str
  2994. Separator between array items for text output.
  2995. If "" (empty), a binary file is written, equivalent to
  2996. ``file.write(a.tobytes())``.
  2997. format : str
  2998. Format string for text file output.
  2999. Each entry in the array is formatted to text by first converting
  3000. it to the closest Python type, and then using "format" % item.
  3001. Notes
  3002. -----
  3003. This is a convenience function for quick storage of array data.
  3004. Information on endianness and precision is lost, so this method is not a
  3005. good choice for files intended to archive data or transport data between
  3006. machines with different endianness. Some of these problems can be overcome
  3007. by outputting the data as text files, at the expense of speed and file
  3008. size.
  3009. When fid is a file object, array contents are directly written to the
  3010. file, bypassing the file object's ``write`` method. As a result, tofile
  3011. cannot be used with files objects supporting compression (e.g., GzipFile)
  3012. or file-like objects that do not support ``fileno()`` (e.g., BytesIO).
  3013. """))
  3014. add_newdoc('numpy.core.multiarray', 'ndarray', ('tolist',
  3015. """
  3016. a.tolist()
  3017. Return the array as an ``a.ndim``-levels deep nested list of Python scalars.
  3018. Return a copy of the array data as a (nested) Python list.
  3019. Data items are converted to the nearest compatible builtin Python type, via
  3020. the `~numpy.ndarray.item` function.
  3021. If ``a.ndim`` is 0, then since the depth of the nested list is 0, it will
  3022. not be a list at all, but a simple Python scalar.
  3023. Parameters
  3024. ----------
  3025. none
  3026. Returns
  3027. -------
  3028. y : object, or list of object, or list of list of object, or ...
  3029. The possibly nested list of array elements.
  3030. Notes
  3031. -----
  3032. The array may be recreated via ``a = np.array(a.tolist())``, although this
  3033. may sometimes lose precision.
  3034. Examples
  3035. --------
  3036. For a 1D array, ``a.tolist()`` is almost the same as ``list(a)``,
  3037. except that ``tolist`` changes numpy scalars to Python scalars:
  3038. >>> a = np.uint32([1, 2])
  3039. >>> a_list = list(a)
  3040. >>> a_list
  3041. [1, 2]
  3042. >>> type(a_list[0])
  3043. <class 'numpy.uint32'>
  3044. >>> a_tolist = a.tolist()
  3045. >>> a_tolist
  3046. [1, 2]
  3047. >>> type(a_tolist[0])
  3048. <class 'int'>
  3049. Additionally, for a 2D array, ``tolist`` applies recursively:
  3050. >>> a = np.array([[1, 2], [3, 4]])
  3051. >>> list(a)
  3052. [array([1, 2]), array([3, 4])]
  3053. >>> a.tolist()
  3054. [[1, 2], [3, 4]]
  3055. The base case for this recursion is a 0D array:
  3056. >>> a = np.array(1)
  3057. >>> list(a)
  3058. Traceback (most recent call last):
  3059. ...
  3060. TypeError: iteration over a 0-d array
  3061. >>> a.tolist()
  3062. 1
  3063. """))
  3064. add_newdoc('numpy.core.multiarray', 'ndarray', ('tobytes', """
  3065. a.tobytes(order='C')
  3066. Construct Python bytes containing the raw data bytes in the array.
  3067. Constructs Python bytes showing a copy of the raw contents of
  3068. data memory. The bytes object is produced in C-order by default.
  3069. This behavior is controlled by the ``order`` parameter.
  3070. .. versionadded:: 1.9.0
  3071. Parameters
  3072. ----------
  3073. order : {'C', 'F', 'A'}, optional
  3074. Controls the memory layout of the bytes object. 'C' means C-order,
  3075. 'F' means F-order, 'A' (short for *Any*) means 'F' if `a` is
  3076. Fortran contiguous, 'C' otherwise. Default is 'C'.
  3077. Returns
  3078. -------
  3079. s : bytes
  3080. Python bytes exhibiting a copy of `a`'s raw data.
  3081. Examples
  3082. --------
  3083. >>> x = np.array([[0, 1], [2, 3]], dtype='<u2')
  3084. >>> x.tobytes()
  3085. b'\\x00\\x00\\x01\\x00\\x02\\x00\\x03\\x00'
  3086. >>> x.tobytes('C') == x.tobytes()
  3087. True
  3088. >>> x.tobytes('F')
  3089. b'\\x00\\x00\\x02\\x00\\x01\\x00\\x03\\x00'
  3090. """))
  3091. add_newdoc('numpy.core.multiarray', 'ndarray', ('tostring', r"""
  3092. a.tostring(order='C')
  3093. A compatibility alias for `tobytes`, with exactly the same behavior.
  3094. Despite its name, it returns `bytes` not `str`\ s.
  3095. .. deprecated:: 1.19.0
  3096. """))
  3097. add_newdoc('numpy.core.multiarray', 'ndarray', ('trace',
  3098. """
  3099. a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
  3100. Return the sum along diagonals of the array.
  3101. Refer to `numpy.trace` for full documentation.
  3102. See Also
  3103. --------
  3104. numpy.trace : equivalent function
  3105. """))
  3106. add_newdoc('numpy.core.multiarray', 'ndarray', ('transpose',
  3107. """
  3108. a.transpose(*axes)
  3109. Returns a view of the array with axes transposed.
  3110. For a 1-D array this has no effect, as a transposed vector is simply the
  3111. same vector. To convert a 1-D array into a 2D column vector, an additional
  3112. dimension must be added. `np.atleast2d(a).T` achieves this, as does
  3113. `a[:, np.newaxis]`.
  3114. For a 2-D array, this is a standard matrix transpose.
  3115. For an n-D array, if axes are given, their order indicates how the
  3116. axes are permuted (see Examples). If axes are not provided and
  3117. ``a.shape = (i[0], i[1], ... i[n-2], i[n-1])``, then
  3118. ``a.transpose().shape = (i[n-1], i[n-2], ... i[1], i[0])``.
  3119. Parameters
  3120. ----------
  3121. axes : None, tuple of ints, or `n` ints
  3122. * None or no argument: reverses the order of the axes.
  3123. * tuple of ints: `i` in the `j`-th place in the tuple means `a`'s
  3124. `i`-th axis becomes `a.transpose()`'s `j`-th axis.
  3125. * `n` ints: same as an n-tuple of the same ints (this form is
  3126. intended simply as a "convenience" alternative to the tuple form)
  3127. Returns
  3128. -------
  3129. out : ndarray
  3130. View of `a`, with axes suitably permuted.
  3131. See Also
  3132. --------
  3133. ndarray.T : Array property returning the array transposed.
  3134. ndarray.reshape : Give a new shape to an array without changing its data.
  3135. Examples
  3136. --------
  3137. >>> a = np.array([[1, 2], [3, 4]])
  3138. >>> a
  3139. array([[1, 2],
  3140. [3, 4]])
  3141. >>> a.transpose()
  3142. array([[1, 3],
  3143. [2, 4]])
  3144. >>> a.transpose((1, 0))
  3145. array([[1, 3],
  3146. [2, 4]])
  3147. >>> a.transpose(1, 0)
  3148. array([[1, 3],
  3149. [2, 4]])
  3150. """))
  3151. add_newdoc('numpy.core.multiarray', 'ndarray', ('var',
  3152. """
  3153. a.var(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)
  3154. Returns the variance of the array elements, along given axis.
  3155. Refer to `numpy.var` for full documentation.
  3156. See Also
  3157. --------
  3158. numpy.var : equivalent function
  3159. """))
  3160. add_newdoc('numpy.core.multiarray', 'ndarray', ('view',
  3161. """
  3162. a.view([dtype][, type])
  3163. New view of array with the same data.
  3164. .. note::
  3165. Passing None for ``dtype`` is different from omitting the parameter,
  3166. since the former invokes ``dtype(None)`` which is an alias for
  3167. ``dtype('float_')``.
  3168. Parameters
  3169. ----------
  3170. dtype : data-type or ndarray sub-class, optional
  3171. Data-type descriptor of the returned view, e.g., float32 or int16.
  3172. Omitting it results in the view having the same data-type as `a`.
  3173. This argument can also be specified as an ndarray sub-class, which
  3174. then specifies the type of the returned object (this is equivalent to
  3175. setting the ``type`` parameter).
  3176. type : Python type, optional
  3177. Type of the returned view, e.g., ndarray or matrix. Again, omission
  3178. of the parameter results in type preservation.
  3179. Notes
  3180. -----
  3181. ``a.view()`` is used two different ways:
  3182. ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view
  3183. of the array's memory with a different data-type. This can cause a
  3184. reinterpretation of the bytes of memory.
  3185. ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just
  3186. returns an instance of `ndarray_subclass` that looks at the same array
  3187. (same shape, dtype, etc.) This does not cause a reinterpretation of the
  3188. memory.
  3189. For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of
  3190. bytes per entry than the previous dtype (for example, converting a
  3191. regular array to a structured array), then the behavior of the view
  3192. cannot be predicted just from the superficial appearance of ``a`` (shown
  3193. by ``print(a)``). It also depends on exactly how ``a`` is stored in
  3194. memory. Therefore if ``a`` is C-ordered versus fortran-ordered, versus
  3195. defined as a slice or transpose, etc., the view may give different
  3196. results.
  3197. Examples
  3198. --------
  3199. >>> x = np.array([(1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
  3200. Viewing array data using a different type and dtype:
  3201. >>> y = x.view(dtype=np.int16, type=np.matrix)
  3202. >>> y
  3203. matrix([[513]], dtype=int16)
  3204. >>> print(type(y))
  3205. <class 'numpy.matrix'>
  3206. Creating a view on a structured array so it can be used in calculations
  3207. >>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)])
  3208. >>> xv = x.view(dtype=np.int8).reshape(-1,2)
  3209. >>> xv
  3210. array([[1, 2],
  3211. [3, 4]], dtype=int8)
  3212. >>> xv.mean(0)
  3213. array([2., 3.])
  3214. Making changes to the view changes the underlying array
  3215. >>> xv[0,1] = 20
  3216. >>> x
  3217. array([(1, 20), (3, 4)], dtype=[('a', 'i1'), ('b', 'i1')])
  3218. Using a view to convert an array to a recarray:
  3219. >>> z = x.view(np.recarray)
  3220. >>> z.a
  3221. array([1, 3], dtype=int8)
  3222. Views share data:
  3223. >>> x[0] = (9, 10)
  3224. >>> z[0]
  3225. (9, 10)
  3226. Views that change the dtype size (bytes per entry) should normally be
  3227. avoided on arrays defined by slices, transposes, fortran-ordering, etc.:
  3228. >>> x = np.array([[1,2,3],[4,5,6]], dtype=np.int16)
  3229. >>> y = x[:, 0:2]
  3230. >>> y
  3231. array([[1, 2],
  3232. [4, 5]], dtype=int16)
  3233. >>> y.view(dtype=[('width', np.int16), ('length', np.int16)])
  3234. Traceback (most recent call last):
  3235. ...
  3236. ValueError: To change to a dtype of a different size, the array must be C-contiguous
  3237. >>> z = y.copy()
  3238. >>> z.view(dtype=[('width', np.int16), ('length', np.int16)])
  3239. array([[(1, 2)],
  3240. [(4, 5)]], dtype=[('width', '<i2'), ('length', '<i2')])
  3241. """))
  3242. ##############################################################################
  3243. #
  3244. # umath functions
  3245. #
  3246. ##############################################################################
  3247. add_newdoc('numpy.core.umath', 'frompyfunc',
  3248. """
  3249. frompyfunc(func, nin, nout, *[, identity])
  3250. Takes an arbitrary Python function and returns a NumPy ufunc.
  3251. Can be used, for example, to add broadcasting to a built-in Python
  3252. function (see Examples section).
  3253. Parameters
  3254. ----------
  3255. func : Python function object
  3256. An arbitrary Python function.
  3257. nin : int
  3258. The number of input arguments.
  3259. nout : int
  3260. The number of objects returned by `func`.
  3261. identity : object, optional
  3262. The value to use for the `~numpy.ufunc.identity` attribute of the resulting
  3263. object. If specified, this is equivalent to setting the underlying
  3264. C ``identity`` field to ``PyUFunc_IdentityValue``.
  3265. If omitted, the identity is set to ``PyUFunc_None``. Note that this is
  3266. _not_ equivalent to setting the identity to ``None``, which implies the
  3267. operation is reorderable.
  3268. Returns
  3269. -------
  3270. out : ufunc
  3271. Returns a NumPy universal function (``ufunc``) object.
  3272. See Also
  3273. --------
  3274. vectorize : Evaluates pyfunc over input arrays using broadcasting rules of numpy.
  3275. Notes
  3276. -----
  3277. The returned ufunc always returns PyObject arrays.
  3278. Examples
  3279. --------
  3280. Use frompyfunc to add broadcasting to the Python function ``oct``:
  3281. >>> oct_array = np.frompyfunc(oct, 1, 1)
  3282. >>> oct_array(np.array((10, 30, 100)))
  3283. array(['0o12', '0o36', '0o144'], dtype=object)
  3284. >>> np.array((oct(10), oct(30), oct(100))) # for comparison
  3285. array(['0o12', '0o36', '0o144'], dtype='<U5')
  3286. """)
  3287. add_newdoc('numpy.core.umath', 'geterrobj',
  3288. """
  3289. geterrobj()
  3290. Return the current object that defines floating-point error handling.
  3291. The error object contains all information that defines the error handling
  3292. behavior in NumPy. `geterrobj` is used internally by the other
  3293. functions that get and set error handling behavior (`geterr`, `seterr`,
  3294. `geterrcall`, `seterrcall`).
  3295. Returns
  3296. -------
  3297. errobj : list
  3298. The error object, a list containing three elements:
  3299. [internal numpy buffer size, error mask, error callback function].
  3300. The error mask is a single integer that holds the treatment information
  3301. on all four floating point errors. The information for each error type
  3302. is contained in three bits of the integer. If we print it in base 8, we
  3303. can see what treatment is set for "invalid", "under", "over", and
  3304. "divide" (in that order). The printed string can be interpreted with
  3305. * 0 : 'ignore'
  3306. * 1 : 'warn'
  3307. * 2 : 'raise'
  3308. * 3 : 'call'
  3309. * 4 : 'print'
  3310. * 5 : 'log'
  3311. See Also
  3312. --------
  3313. seterrobj, seterr, geterr, seterrcall, geterrcall
  3314. getbufsize, setbufsize
  3315. Notes
  3316. -----
  3317. For complete documentation of the types of floating-point exceptions and
  3318. treatment options, see `seterr`.
  3319. Examples
  3320. --------
  3321. >>> np.geterrobj() # first get the defaults
  3322. [8192, 521, None]
  3323. >>> def err_handler(type, flag):
  3324. ... print("Floating point error (%s), with flag %s" % (type, flag))
  3325. ...
  3326. >>> old_bufsize = np.setbufsize(20000)
  3327. >>> old_err = np.seterr(divide='raise')
  3328. >>> old_handler = np.seterrcall(err_handler)
  3329. >>> np.geterrobj()
  3330. [8192, 521, <function err_handler at 0x91dcaac>]
  3331. >>> old_err = np.seterr(all='ignore')
  3332. >>> np.base_repr(np.geterrobj()[1], 8)
  3333. '0'
  3334. >>> old_err = np.seterr(divide='warn', over='log', under='call',
  3335. ... invalid='print')
  3336. >>> np.base_repr(np.geterrobj()[1], 8)
  3337. '4351'
  3338. """)
  3339. add_newdoc('numpy.core.umath', 'seterrobj',
  3340. """
  3341. seterrobj(errobj)
  3342. Set the object that defines floating-point error handling.
  3343. The error object contains all information that defines the error handling
  3344. behavior in NumPy. `seterrobj` is used internally by the other
  3345. functions that set error handling behavior (`seterr`, `seterrcall`).
  3346. Parameters
  3347. ----------
  3348. errobj : list
  3349. The error object, a list containing three elements:
  3350. [internal numpy buffer size, error mask, error callback function].
  3351. The error mask is a single integer that holds the treatment information
  3352. on all four floating point errors. The information for each error type
  3353. is contained in three bits of the integer. If we print it in base 8, we
  3354. can see what treatment is set for "invalid", "under", "over", and
  3355. "divide" (in that order). The printed string can be interpreted with
  3356. * 0 : 'ignore'
  3357. * 1 : 'warn'
  3358. * 2 : 'raise'
  3359. * 3 : 'call'
  3360. * 4 : 'print'
  3361. * 5 : 'log'
  3362. See Also
  3363. --------
  3364. geterrobj, seterr, geterr, seterrcall, geterrcall
  3365. getbufsize, setbufsize
  3366. Notes
  3367. -----
  3368. For complete documentation of the types of floating-point exceptions and
  3369. treatment options, see `seterr`.
  3370. Examples
  3371. --------
  3372. >>> old_errobj = np.geterrobj() # first get the defaults
  3373. >>> old_errobj
  3374. [8192, 521, None]
  3375. >>> def err_handler(type, flag):
  3376. ... print("Floating point error (%s), with flag %s" % (type, flag))
  3377. ...
  3378. >>> new_errobj = [20000, 12, err_handler]
  3379. >>> np.seterrobj(new_errobj)
  3380. >>> np.base_repr(12, 8) # int for divide=4 ('print') and over=1 ('warn')
  3381. '14'
  3382. >>> np.geterr()
  3383. {'over': 'warn', 'divide': 'print', 'invalid': 'ignore', 'under': 'ignore'}
  3384. >>> np.geterrcall() is err_handler
  3385. True
  3386. """)
  3387. ##############################################################################
  3388. #
  3389. # compiled_base functions
  3390. #
  3391. ##############################################################################
  3392. add_newdoc('numpy.core.multiarray', 'add_docstring',
  3393. """
  3394. add_docstring(obj, docstring)
  3395. Add a docstring to a built-in obj if possible.
  3396. If the obj already has a docstring raise a RuntimeError
  3397. If this routine does not know how to add a docstring to the object
  3398. raise a TypeError
  3399. """)
  3400. add_newdoc('numpy.core.umath', '_add_newdoc_ufunc',
  3401. """
  3402. add_ufunc_docstring(ufunc, new_docstring)
  3403. Replace the docstring for a ufunc with new_docstring.
  3404. This method will only work if the current docstring for
  3405. the ufunc is NULL. (At the C level, i.e. when ufunc->doc is NULL.)
  3406. Parameters
  3407. ----------
  3408. ufunc : numpy.ufunc
  3409. A ufunc whose current doc is NULL.
  3410. new_docstring : string
  3411. The new docstring for the ufunc.
  3412. Notes
  3413. -----
  3414. This method allocates memory for new_docstring on
  3415. the heap. Technically this creates a mempory leak, since this
  3416. memory will not be reclaimed until the end of the program
  3417. even if the ufunc itself is removed. However this will only
  3418. be a problem if the user is repeatedly creating ufuncs with
  3419. no documentation, adding documentation via add_newdoc_ufunc,
  3420. and then throwing away the ufunc.
  3421. """)
  3422. add_newdoc('numpy.core.multiarray', '_set_madvise_hugepage',
  3423. """
  3424. _set_madvise_hugepage(enabled: bool) -> bool
  3425. Set or unset use of ``madvise (2)`` MADV_HUGEPAGE support when
  3426. allocating the array data. Returns the previously set value.
  3427. See `global_state` for more information.
  3428. """)
  3429. add_newdoc('numpy.core._multiarray_tests', 'format_float_OSprintf_g',
  3430. """
  3431. format_float_OSprintf_g(val, precision)
  3432. Print a floating point scalar using the system's printf function,
  3433. equivalent to:
  3434. printf("%.*g", precision, val);
  3435. for half/float/double, or replacing 'g' by 'Lg' for longdouble. This
  3436. method is designed to help cross-validate the format_float_* methods.
  3437. Parameters
  3438. ----------
  3439. val : python float or numpy floating scalar
  3440. Value to format.
  3441. precision : non-negative integer, optional
  3442. Precision given to printf.
  3443. Returns
  3444. -------
  3445. rep : string
  3446. The string representation of the floating point value
  3447. See Also
  3448. --------
  3449. format_float_scientific
  3450. format_float_positional
  3451. """)
  3452. ##############################################################################
  3453. #
  3454. # Documentation for ufunc attributes and methods
  3455. #
  3456. ##############################################################################
  3457. ##############################################################################
  3458. #
  3459. # ufunc object
  3460. #
  3461. ##############################################################################
  3462. add_newdoc('numpy.core', 'ufunc',
  3463. """
  3464. Functions that operate element by element on whole arrays.
  3465. To see the documentation for a specific ufunc, use `info`. For
  3466. example, ``np.info(np.sin)``. Because ufuncs are written in C
  3467. (for speed) and linked into Python with NumPy's ufunc facility,
  3468. Python's help() function finds this page whenever help() is called
  3469. on a ufunc.
  3470. A detailed explanation of ufuncs can be found in the docs for :ref:`ufuncs`.
  3471. **Calling ufuncs:** ``op(*x[, out], where=True, **kwargs)``
  3472. Apply `op` to the arguments `*x` elementwise, broadcasting the arguments.
  3473. The broadcasting rules are:
  3474. * Dimensions of length 1 may be prepended to either array.
  3475. * Arrays may be repeated along dimensions of length 1.
  3476. Parameters
  3477. ----------
  3478. *x : array_like
  3479. Input arrays.
  3480. out : ndarray, None, or tuple of ndarray and None, optional
  3481. Alternate array object(s) in which to put the result; if provided, it
  3482. must have a shape that the inputs broadcast to. A tuple of arrays
  3483. (possible only as a keyword argument) must have length equal to the
  3484. number of outputs; use None for uninitialized outputs to be
  3485. allocated by the ufunc.
  3486. where : array_like, optional
  3487. This condition is broadcast over the input. At locations where the
  3488. condition is True, the `out` array will be set to the ufunc result.
  3489. Elsewhere, the `out` array will retain its original value.
  3490. Note that if an uninitialized `out` array is created via the default
  3491. ``out=None``, locations within it where the condition is False will
  3492. remain uninitialized.
  3493. **kwargs
  3494. For other keyword-only arguments, see the :ref:`ufunc docs <ufuncs.kwargs>`.
  3495. Returns
  3496. -------
  3497. r : ndarray or tuple of ndarray
  3498. `r` will have the shape that the arrays in `x` broadcast to; if `out` is
  3499. provided, it will be returned. If not, `r` will be allocated and
  3500. may contain uninitialized values. If the function has more than one
  3501. output, then the result will be a tuple of arrays.
  3502. """)
  3503. ##############################################################################
  3504. #
  3505. # ufunc attributes
  3506. #
  3507. ##############################################################################
  3508. add_newdoc('numpy.core', 'ufunc', ('identity',
  3509. """
  3510. The identity value.
  3511. Data attribute containing the identity element for the ufunc, if it has one.
  3512. If it does not, the attribute value is None.
  3513. Examples
  3514. --------
  3515. >>> np.add.identity
  3516. 0
  3517. >>> np.multiply.identity
  3518. 1
  3519. >>> np.power.identity
  3520. 1
  3521. >>> print(np.exp.identity)
  3522. None
  3523. """))
  3524. add_newdoc('numpy.core', 'ufunc', ('nargs',
  3525. """
  3526. The number of arguments.
  3527. Data attribute containing the number of arguments the ufunc takes, including
  3528. optional ones.
  3529. Notes
  3530. -----
  3531. Typically this value will be one more than what you might expect because all
  3532. ufuncs take the optional "out" argument.
  3533. Examples
  3534. --------
  3535. >>> np.add.nargs
  3536. 3
  3537. >>> np.multiply.nargs
  3538. 3
  3539. >>> np.power.nargs
  3540. 3
  3541. >>> np.exp.nargs
  3542. 2
  3543. """))
  3544. add_newdoc('numpy.core', 'ufunc', ('nin',
  3545. """
  3546. The number of inputs.
  3547. Data attribute containing the number of arguments the ufunc treats as input.
  3548. Examples
  3549. --------
  3550. >>> np.add.nin
  3551. 2
  3552. >>> np.multiply.nin
  3553. 2
  3554. >>> np.power.nin
  3555. 2
  3556. >>> np.exp.nin
  3557. 1
  3558. """))
  3559. add_newdoc('numpy.core', 'ufunc', ('nout',
  3560. """
  3561. The number of outputs.
  3562. Data attribute containing the number of arguments the ufunc treats as output.
  3563. Notes
  3564. -----
  3565. Since all ufuncs can take output arguments, this will always be (at least) 1.
  3566. Examples
  3567. --------
  3568. >>> np.add.nout
  3569. 1
  3570. >>> np.multiply.nout
  3571. 1
  3572. >>> np.power.nout
  3573. 1
  3574. >>> np.exp.nout
  3575. 1
  3576. """))
  3577. add_newdoc('numpy.core', 'ufunc', ('ntypes',
  3578. """
  3579. The number of types.
  3580. The number of numerical NumPy types - of which there are 18 total - on which
  3581. the ufunc can operate.
  3582. See Also
  3583. --------
  3584. numpy.ufunc.types
  3585. Examples
  3586. --------
  3587. >>> np.add.ntypes
  3588. 18
  3589. >>> np.multiply.ntypes
  3590. 18
  3591. >>> np.power.ntypes
  3592. 17
  3593. >>> np.exp.ntypes
  3594. 7
  3595. >>> np.remainder.ntypes
  3596. 14
  3597. """))
  3598. add_newdoc('numpy.core', 'ufunc', ('types',
  3599. """
  3600. Returns a list with types grouped input->output.
  3601. Data attribute listing the data-type "Domain-Range" groupings the ufunc can
  3602. deliver. The data-types are given using the character codes.
  3603. See Also
  3604. --------
  3605. numpy.ufunc.ntypes
  3606. Examples
  3607. --------
  3608. >>> np.add.types
  3609. ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l',
  3610. 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D',
  3611. 'GG->G', 'OO->O']
  3612. >>> np.multiply.types
  3613. ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l',
  3614. 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D',
  3615. 'GG->G', 'OO->O']
  3616. >>> np.power.types
  3617. ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L',
  3618. 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', 'GG->G',
  3619. 'OO->O']
  3620. >>> np.exp.types
  3621. ['f->f', 'd->d', 'g->g', 'F->F', 'D->D', 'G->G', 'O->O']
  3622. >>> np.remainder.types
  3623. ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L',
  3624. 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'OO->O']
  3625. """))
  3626. add_newdoc('numpy.core', 'ufunc', ('signature',
  3627. """
  3628. Definition of the core elements a generalized ufunc operates on.
  3629. The signature determines how the dimensions of each input/output array
  3630. are split into core and loop dimensions:
  3631. 1. Each dimension in the signature is matched to a dimension of the
  3632. corresponding passed-in array, starting from the end of the shape tuple.
  3633. 2. Core dimensions assigned to the same label in the signature must have
  3634. exactly matching sizes, no broadcasting is performed.
  3635. 3. The core dimensions are removed from all inputs and the remaining
  3636. dimensions are broadcast together, defining the loop dimensions.
  3637. Notes
  3638. -----
  3639. Generalized ufuncs are used internally in many linalg functions, and in
  3640. the testing suite; the examples below are taken from these.
  3641. For ufuncs that operate on scalars, the signature is None, which is
  3642. equivalent to '()' for every argument.
  3643. Examples
  3644. --------
  3645. >>> np.core.umath_tests.matrix_multiply.signature
  3646. '(m,n),(n,p)->(m,p)'
  3647. >>> np.linalg._umath_linalg.det.signature
  3648. '(m,m)->()'
  3649. >>> np.add.signature is None
  3650. True # equivalent to '(),()->()'
  3651. """))
  3652. ##############################################################################
  3653. #
  3654. # ufunc methods
  3655. #
  3656. ##############################################################################
  3657. add_newdoc('numpy.core', 'ufunc', ('reduce',
  3658. """
  3659. reduce(array, axis=0, dtype=None, out=None, keepdims=False, initial=<no value>, where=True)
  3660. Reduces `array`'s dimension by one, by applying ufunc along one axis.
  3661. Let :math:`array.shape = (N_0, ..., N_i, ..., N_{M-1})`. Then
  3662. :math:`ufunc.reduce(array, axis=i)[k_0, ..,k_{i-1}, k_{i+1}, .., k_{M-1}]` =
  3663. the result of iterating `j` over :math:`range(N_i)`, cumulatively applying
  3664. ufunc to each :math:`array[k_0, ..,k_{i-1}, j, k_{i+1}, .., k_{M-1}]`.
  3665. For a one-dimensional array, reduce produces results equivalent to:
  3666. ::
  3667. r = op.identity # op = ufunc
  3668. for i in range(len(A)):
  3669. r = op(r, A[i])
  3670. return r
  3671. For example, add.reduce() is equivalent to sum().
  3672. Parameters
  3673. ----------
  3674. array : array_like
  3675. The array to act on.
  3676. axis : None or int or tuple of ints, optional
  3677. Axis or axes along which a reduction is performed.
  3678. The default (`axis` = 0) is perform a reduction over the first
  3679. dimension of the input array. `axis` may be negative, in
  3680. which case it counts from the last to the first axis.
  3681. .. versionadded:: 1.7.0
  3682. If this is None, a reduction is performed over all the axes.
  3683. If this is a tuple of ints, a reduction is performed on multiple
  3684. axes, instead of a single axis or all the axes as before.
  3685. For operations which are either not commutative or not associative,
  3686. doing a reduction over multiple axes is not well-defined. The
  3687. ufuncs do not currently raise an exception in this case, but will
  3688. likely do so in the future.
  3689. dtype : data-type code, optional
  3690. The type used to represent the intermediate results. Defaults
  3691. to the data-type of the output array if this is provided, or
  3692. the data-type of the input array if no output array is provided.
  3693. out : ndarray, None, or tuple of ndarray and None, optional
  3694. A location into which the result is stored. If not provided or None,
  3695. a freshly-allocated array is returned. For consistency with
  3696. ``ufunc.__call__``, if given as a keyword, this may be wrapped in a
  3697. 1-element tuple.
  3698. .. versionchanged:: 1.13.0
  3699. Tuples are allowed for keyword argument.
  3700. keepdims : bool, optional
  3701. If this is set to True, the axes which are reduced are left
  3702. in the result as dimensions with size one. With this option,
  3703. the result will broadcast correctly against the original `array`.
  3704. .. versionadded:: 1.7.0
  3705. initial : scalar, optional
  3706. The value with which to start the reduction.
  3707. If the ufunc has no identity or the dtype is object, this defaults
  3708. to None - otherwise it defaults to ufunc.identity.
  3709. If ``None`` is given, the first element of the reduction is used,
  3710. and an error is thrown if the reduction is empty.
  3711. .. versionadded:: 1.15.0
  3712. where : array_like of bool, optional
  3713. A boolean array which is broadcasted to match the dimensions
  3714. of `array`, and selects elements to include in the reduction. Note
  3715. that for ufuncs like ``minimum`` that do not have an identity
  3716. defined, one has to pass in also ``initial``.
  3717. .. versionadded:: 1.17.0
  3718. Returns
  3719. -------
  3720. r : ndarray
  3721. The reduced array. If `out` was supplied, `r` is a reference to it.
  3722. Examples
  3723. --------
  3724. >>> np.multiply.reduce([2,3,5])
  3725. 30
  3726. A multi-dimensional array example:
  3727. >>> X = np.arange(8).reshape((2,2,2))
  3728. >>> X
  3729. array([[[0, 1],
  3730. [2, 3]],
  3731. [[4, 5],
  3732. [6, 7]]])
  3733. >>> np.add.reduce(X, 0)
  3734. array([[ 4, 6],
  3735. [ 8, 10]])
  3736. >>> np.add.reduce(X) # confirm: default axis value is 0
  3737. array([[ 4, 6],
  3738. [ 8, 10]])
  3739. >>> np.add.reduce(X, 1)
  3740. array([[ 2, 4],
  3741. [10, 12]])
  3742. >>> np.add.reduce(X, 2)
  3743. array([[ 1, 5],
  3744. [ 9, 13]])
  3745. You can use the ``initial`` keyword argument to initialize the reduction
  3746. with a different value, and ``where`` to select specific elements to include:
  3747. >>> np.add.reduce([10], initial=5)
  3748. 15
  3749. >>> np.add.reduce(np.ones((2, 2, 2)), axis=(0, 2), initial=10)
  3750. array([14., 14.])
  3751. >>> a = np.array([10., np.nan, 10])
  3752. >>> np.add.reduce(a, where=~np.isnan(a))
  3753. 20.0
  3754. Allows reductions of empty arrays where they would normally fail, i.e.
  3755. for ufuncs without an identity.
  3756. >>> np.minimum.reduce([], initial=np.inf)
  3757. inf
  3758. >>> np.minimum.reduce([[1., 2.], [3., 4.]], initial=10., where=[True, False])
  3759. array([ 1., 10.])
  3760. >>> np.minimum.reduce([])
  3761. Traceback (most recent call last):
  3762. ...
  3763. ValueError: zero-size array to reduction operation minimum which has no identity
  3764. """))
  3765. add_newdoc('numpy.core', 'ufunc', ('accumulate',
  3766. """
  3767. accumulate(array, axis=0, dtype=None, out=None)
  3768. Accumulate the result of applying the operator to all elements.
  3769. For a one-dimensional array, accumulate produces results equivalent to::
  3770. r = np.empty(len(A))
  3771. t = op.identity # op = the ufunc being applied to A's elements
  3772. for i in range(len(A)):
  3773. t = op(t, A[i])
  3774. r[i] = t
  3775. return r
  3776. For example, add.accumulate() is equivalent to np.cumsum().
  3777. For a multi-dimensional array, accumulate is applied along only one
  3778. axis (axis zero by default; see Examples below) so repeated use is
  3779. necessary if one wants to accumulate over multiple axes.
  3780. Parameters
  3781. ----------
  3782. array : array_like
  3783. The array to act on.
  3784. axis : int, optional
  3785. The axis along which to apply the accumulation; default is zero.
  3786. dtype : data-type code, optional
  3787. The data-type used to represent the intermediate results. Defaults
  3788. to the data-type of the output array if such is provided, or the
  3789. the data-type of the input array if no output array is provided.
  3790. out : ndarray, None, or tuple of ndarray and None, optional
  3791. A location into which the result is stored. If not provided or None,
  3792. a freshly-allocated array is returned. For consistency with
  3793. ``ufunc.__call__``, if given as a keyword, this may be wrapped in a
  3794. 1-element tuple.
  3795. .. versionchanged:: 1.13.0
  3796. Tuples are allowed for keyword argument.
  3797. Returns
  3798. -------
  3799. r : ndarray
  3800. The accumulated values. If `out` was supplied, `r` is a reference to
  3801. `out`.
  3802. Examples
  3803. --------
  3804. 1-D array examples:
  3805. >>> np.add.accumulate([2, 3, 5])
  3806. array([ 2, 5, 10])
  3807. >>> np.multiply.accumulate([2, 3, 5])
  3808. array([ 2, 6, 30])
  3809. 2-D array examples:
  3810. >>> I = np.eye(2)
  3811. >>> I
  3812. array([[1., 0.],
  3813. [0., 1.]])
  3814. Accumulate along axis 0 (rows), down columns:
  3815. >>> np.add.accumulate(I, 0)
  3816. array([[1., 0.],
  3817. [1., 1.]])
  3818. >>> np.add.accumulate(I) # no axis specified = axis zero
  3819. array([[1., 0.],
  3820. [1., 1.]])
  3821. Accumulate along axis 1 (columns), through rows:
  3822. >>> np.add.accumulate(I, 1)
  3823. array([[1., 1.],
  3824. [0., 1.]])
  3825. """))
  3826. add_newdoc('numpy.core', 'ufunc', ('reduceat',
  3827. """
  3828. reduceat(array, indices, axis=0, dtype=None, out=None)
  3829. Performs a (local) reduce with specified slices over a single axis.
  3830. For i in ``range(len(indices))``, `reduceat` computes
  3831. ``ufunc.reduce(array[indices[i]:indices[i+1]])``, which becomes the i-th
  3832. generalized "row" parallel to `axis` in the final result (i.e., in a
  3833. 2-D array, for example, if `axis = 0`, it becomes the i-th row, but if
  3834. `axis = 1`, it becomes the i-th column). There are three exceptions to this:
  3835. * when ``i = len(indices) - 1`` (so for the last index),
  3836. ``indices[i+1] = array.shape[axis]``.
  3837. * if ``indices[i] >= indices[i + 1]``, the i-th generalized "row" is
  3838. simply ``array[indices[i]]``.
  3839. * if ``indices[i] >= len(array)`` or ``indices[i] < 0``, an error is raised.
  3840. The shape of the output depends on the size of `indices`, and may be
  3841. larger than `array` (this happens if ``len(indices) > array.shape[axis]``).
  3842. Parameters
  3843. ----------
  3844. array : array_like
  3845. The array to act on.
  3846. indices : array_like
  3847. Paired indices, comma separated (not colon), specifying slices to
  3848. reduce.
  3849. axis : int, optional
  3850. The axis along which to apply the reduceat.
  3851. dtype : data-type code, optional
  3852. The type used to represent the intermediate results. Defaults
  3853. to the data type of the output array if this is provided, or
  3854. the data type of the input array if no output array is provided.
  3855. out : ndarray, None, or tuple of ndarray and None, optional
  3856. A location into which the result is stored. If not provided or None,
  3857. a freshly-allocated array is returned. For consistency with
  3858. ``ufunc.__call__``, if given as a keyword, this may be wrapped in a
  3859. 1-element tuple.
  3860. .. versionchanged:: 1.13.0
  3861. Tuples are allowed for keyword argument.
  3862. Returns
  3863. -------
  3864. r : ndarray
  3865. The reduced values. If `out` was supplied, `r` is a reference to
  3866. `out`.
  3867. Notes
  3868. -----
  3869. A descriptive example:
  3870. If `array` is 1-D, the function `ufunc.accumulate(array)` is the same as
  3871. ``ufunc.reduceat(array, indices)[::2]`` where `indices` is
  3872. ``range(len(array) - 1)`` with a zero placed
  3873. in every other element:
  3874. ``indices = zeros(2 * len(array) - 1)``,
  3875. ``indices[1::2] = range(1, len(array))``.
  3876. Don't be fooled by this attribute's name: `reduceat(array)` is not
  3877. necessarily smaller than `array`.
  3878. Examples
  3879. --------
  3880. To take the running sum of four successive values:
  3881. >>> np.add.reduceat(np.arange(8),[0,4, 1,5, 2,6, 3,7])[::2]
  3882. array([ 6, 10, 14, 18])
  3883. A 2-D example:
  3884. >>> x = np.linspace(0, 15, 16).reshape(4,4)
  3885. >>> x
  3886. array([[ 0., 1., 2., 3.],
  3887. [ 4., 5., 6., 7.],
  3888. [ 8., 9., 10., 11.],
  3889. [12., 13., 14., 15.]])
  3890. ::
  3891. # reduce such that the result has the following five rows:
  3892. # [row1 + row2 + row3]
  3893. # [row4]
  3894. # [row2]
  3895. # [row3]
  3896. # [row1 + row2 + row3 + row4]
  3897. >>> np.add.reduceat(x, [0, 3, 1, 2, 0])
  3898. array([[12., 15., 18., 21.],
  3899. [12., 13., 14., 15.],
  3900. [ 4., 5., 6., 7.],
  3901. [ 8., 9., 10., 11.],
  3902. [24., 28., 32., 36.]])
  3903. ::
  3904. # reduce such that result has the following two columns:
  3905. # [col1 * col2 * col3, col4]
  3906. >>> np.multiply.reduceat(x, [0, 3], 1)
  3907. array([[ 0., 3.],
  3908. [ 120., 7.],
  3909. [ 720., 11.],
  3910. [2184., 15.]])
  3911. """))
  3912. add_newdoc('numpy.core', 'ufunc', ('outer',
  3913. r"""
  3914. outer(A, B, /, **kwargs)
  3915. Apply the ufunc `op` to all pairs (a, b) with a in `A` and b in `B`.
  3916. Let ``M = A.ndim``, ``N = B.ndim``. Then the result, `C`, of
  3917. ``op.outer(A, B)`` is an array of dimension M + N such that:
  3918. .. math:: C[i_0, ..., i_{M-1}, j_0, ..., j_{N-1}] =
  3919. op(A[i_0, ..., i_{M-1}], B[j_0, ..., j_{N-1}])
  3920. For `A` and `B` one-dimensional, this is equivalent to::
  3921. r = empty(len(A),len(B))
  3922. for i in range(len(A)):
  3923. for j in range(len(B)):
  3924. r[i,j] = op(A[i], B[j]) # op = ufunc in question
  3925. Parameters
  3926. ----------
  3927. A : array_like
  3928. First array
  3929. B : array_like
  3930. Second array
  3931. kwargs : any
  3932. Arguments to pass on to the ufunc. Typically `dtype` or `out`.
  3933. Returns
  3934. -------
  3935. r : ndarray
  3936. Output array
  3937. See Also
  3938. --------
  3939. numpy.outer : A less powerful version of ``np.multiply.outer``
  3940. that `ravel`\ s all inputs to 1D. This exists
  3941. primarily for compatibility with old code.
  3942. tensordot : ``np.tensordot(a, b, axes=((), ()))`` and
  3943. ``np.multiply.outer(a, b)`` behave same for all
  3944. dimensions of a and b.
  3945. Examples
  3946. --------
  3947. >>> np.multiply.outer([1, 2, 3], [4, 5, 6])
  3948. array([[ 4, 5, 6],
  3949. [ 8, 10, 12],
  3950. [12, 15, 18]])
  3951. A multi-dimensional example:
  3952. >>> A = np.array([[1, 2, 3], [4, 5, 6]])
  3953. >>> A.shape
  3954. (2, 3)
  3955. >>> B = np.array([[1, 2, 3, 4]])
  3956. >>> B.shape
  3957. (1, 4)
  3958. >>> C = np.multiply.outer(A, B)
  3959. >>> C.shape; C
  3960. (2, 3, 1, 4)
  3961. array([[[[ 1, 2, 3, 4]],
  3962. [[ 2, 4, 6, 8]],
  3963. [[ 3, 6, 9, 12]]],
  3964. [[[ 4, 8, 12, 16]],
  3965. [[ 5, 10, 15, 20]],
  3966. [[ 6, 12, 18, 24]]]])
  3967. """))
  3968. add_newdoc('numpy.core', 'ufunc', ('at',
  3969. """
  3970. at(a, indices, b=None, /)
  3971. Performs unbuffered in place operation on operand 'a' for elements
  3972. specified by 'indices'. For addition ufunc, this method is equivalent to
  3973. ``a[indices] += b``, except that results are accumulated for elements that
  3974. are indexed more than once. For example, ``a[[0,0]] += 1`` will only
  3975. increment the first element once because of buffering, whereas
  3976. ``add.at(a, [0,0], 1)`` will increment the first element twice.
  3977. .. versionadded:: 1.8.0
  3978. Parameters
  3979. ----------
  3980. a : array_like
  3981. The array to perform in place operation on.
  3982. indices : array_like or tuple
  3983. Array like index object or slice object for indexing into first
  3984. operand. If first operand has multiple dimensions, indices can be a
  3985. tuple of array like index objects or slice objects.
  3986. b : array_like
  3987. Second operand for ufuncs requiring two operands. Operand must be
  3988. broadcastable over first operand after indexing or slicing.
  3989. Examples
  3990. --------
  3991. Set items 0 and 1 to their negative values:
  3992. >>> a = np.array([1, 2, 3, 4])
  3993. >>> np.negative.at(a, [0, 1])
  3994. >>> a
  3995. array([-1, -2, 3, 4])
  3996. Increment items 0 and 1, and increment item 2 twice:
  3997. >>> a = np.array([1, 2, 3, 4])
  3998. >>> np.add.at(a, [0, 1, 2, 2], 1)
  3999. >>> a
  4000. array([2, 3, 5, 4])
  4001. Add items 0 and 1 in first array to second array,
  4002. and store results in first array:
  4003. >>> a = np.array([1, 2, 3, 4])
  4004. >>> b = np.array([1, 2])
  4005. >>> np.add.at(a, [0, 1], b)
  4006. >>> a
  4007. array([2, 4, 3, 4])
  4008. """))
  4009. ##############################################################################
  4010. #
  4011. # Documentation for dtype attributes and methods
  4012. #
  4013. ##############################################################################
  4014. ##############################################################################
  4015. #
  4016. # dtype object
  4017. #
  4018. ##############################################################################
  4019. add_newdoc('numpy.core.multiarray', 'dtype',
  4020. """
  4021. dtype(dtype, align=False, copy=False)
  4022. Create a data type object.
  4023. A numpy array is homogeneous, and contains elements described by a
  4024. dtype object. A dtype object can be constructed from different
  4025. combinations of fundamental numeric types.
  4026. Parameters
  4027. ----------
  4028. dtype
  4029. Object to be converted to a data type object.
  4030. align : bool, optional
  4031. Add padding to the fields to match what a C compiler would output
  4032. for a similar C-struct. Can be ``True`` only if `obj` is a dictionary
  4033. or a comma-separated string. If a struct dtype is being created,
  4034. this also sets a sticky alignment flag ``isalignedstruct``.
  4035. copy : bool, optional
  4036. Make a new copy of the data-type object. If ``False``, the result
  4037. may just be a reference to a built-in data-type object.
  4038. See also
  4039. --------
  4040. result_type
  4041. Examples
  4042. --------
  4043. Using array-scalar type:
  4044. >>> np.dtype(np.int16)
  4045. dtype('int16')
  4046. Structured type, one field name 'f1', containing int16:
  4047. >>> np.dtype([('f1', np.int16)])
  4048. dtype([('f1', '<i2')])
  4049. Structured type, one field named 'f1', in itself containing a structured
  4050. type with one field:
  4051. >>> np.dtype([('f1', [('f1', np.int16)])])
  4052. dtype([('f1', [('f1', '<i2')])])
  4053. Structured type, two fields: the first field contains an unsigned int, the
  4054. second an int32:
  4055. >>> np.dtype([('f1', np.uint64), ('f2', np.int32)])
  4056. dtype([('f1', '<u8'), ('f2', '<i4')])
  4057. Using array-protocol type strings:
  4058. >>> np.dtype([('a','f8'),('b','S10')])
  4059. dtype([('a', '<f8'), ('b', 'S10')])
  4060. Using comma-separated field formats. The shape is (2,3):
  4061. >>> np.dtype("i4, (2,3)f8")
  4062. dtype([('f0', '<i4'), ('f1', '<f8', (2, 3))])
  4063. Using tuples. ``int`` is a fixed type, 3 the field's shape. ``void``
  4064. is a flexible type, here of size 10:
  4065. >>> np.dtype([('hello',(np.int64,3)),('world',np.void,10)])
  4066. dtype([('hello', '<i8', (3,)), ('world', 'V10')])
  4067. Subdivide ``int16`` into 2 ``int8``'s, called x and y. 0 and 1 are
  4068. the offsets in bytes:
  4069. >>> np.dtype((np.int16, {'x':(np.int8,0), 'y':(np.int8,1)}))
  4070. dtype((numpy.int16, [('x', 'i1'), ('y', 'i1')]))
  4071. Using dictionaries. Two fields named 'gender' and 'age':
  4072. >>> np.dtype({'names':['gender','age'], 'formats':['S1',np.uint8]})
  4073. dtype([('gender', 'S1'), ('age', 'u1')])
  4074. Offsets in bytes, here 0 and 25:
  4075. >>> np.dtype({'surname':('S25',0),'age':(np.uint8,25)})
  4076. dtype([('surname', 'S25'), ('age', 'u1')])
  4077. """)
  4078. ##############################################################################
  4079. #
  4080. # dtype attributes
  4081. #
  4082. ##############################################################################
  4083. add_newdoc('numpy.core.multiarray', 'dtype', ('alignment',
  4084. """
  4085. The required alignment (bytes) of this data-type according to the compiler.
  4086. More information is available in the C-API section of the manual.
  4087. Examples
  4088. --------
  4089. >>> x = np.dtype('i4')
  4090. >>> x.alignment
  4091. 4
  4092. >>> x = np.dtype(float)
  4093. >>> x.alignment
  4094. 8
  4095. """))
  4096. add_newdoc('numpy.core.multiarray', 'dtype', ('byteorder',
  4097. """
  4098. A character indicating the byte-order of this data-type object.
  4099. One of:
  4100. === ==============
  4101. '=' native
  4102. '<' little-endian
  4103. '>' big-endian
  4104. '|' not applicable
  4105. === ==============
  4106. All built-in data-type objects have byteorder either '=' or '|'.
  4107. Examples
  4108. --------
  4109. >>> dt = np.dtype('i2')
  4110. >>> dt.byteorder
  4111. '='
  4112. >>> # endian is not relevant for 8 bit numbers
  4113. >>> np.dtype('i1').byteorder
  4114. '|'
  4115. >>> # or ASCII strings
  4116. >>> np.dtype('S2').byteorder
  4117. '|'
  4118. >>> # Even if specific code is given, and it is native
  4119. >>> # '=' is the byteorder
  4120. >>> import sys
  4121. >>> sys_is_le = sys.byteorder == 'little'
  4122. >>> native_code = sys_is_le and '<' or '>'
  4123. >>> swapped_code = sys_is_le and '>' or '<'
  4124. >>> dt = np.dtype(native_code + 'i2')
  4125. >>> dt.byteorder
  4126. '='
  4127. >>> # Swapped code shows up as itself
  4128. >>> dt = np.dtype(swapped_code + 'i2')
  4129. >>> dt.byteorder == swapped_code
  4130. True
  4131. """))
  4132. add_newdoc('numpy.core.multiarray', 'dtype', ('char',
  4133. """A unique character code for each of the 21 different built-in types.
  4134. Examples
  4135. --------
  4136. >>> x = np.dtype(float)
  4137. >>> x.char
  4138. 'd'
  4139. """))
  4140. add_newdoc('numpy.core.multiarray', 'dtype', ('descr',
  4141. """
  4142. `__array_interface__` description of the data-type.
  4143. The format is that required by the 'descr' key in the
  4144. `__array_interface__` attribute.
  4145. Warning: This attribute exists specifically for `__array_interface__`,
  4146. and passing it directly to `np.dtype` will not accurately reconstruct
  4147. some dtypes (e.g., scalar and subarray dtypes).
  4148. Examples
  4149. --------
  4150. >>> x = np.dtype(float)
  4151. >>> x.descr
  4152. [('', '<f8')]
  4153. >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
  4154. >>> dt.descr
  4155. [('name', '<U16'), ('grades', '<f8', (2,))]
  4156. """))
  4157. add_newdoc('numpy.core.multiarray', 'dtype', ('fields',
  4158. """
  4159. Dictionary of named fields defined for this data type, or ``None``.
  4160. The dictionary is indexed by keys that are the names of the fields.
  4161. Each entry in the dictionary is a tuple fully describing the field::
  4162. (dtype, offset[, title])
  4163. Offset is limited to C int, which is signed and usually 32 bits.
  4164. If present, the optional title can be any object (if it is a string
  4165. or unicode then it will also be a key in the fields dictionary,
  4166. otherwise it's meta-data). Notice also that the first two elements
  4167. of the tuple can be passed directly as arguments to the ``ndarray.getfield``
  4168. and ``ndarray.setfield`` methods.
  4169. See Also
  4170. --------
  4171. ndarray.getfield, ndarray.setfield
  4172. Examples
  4173. --------
  4174. >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
  4175. >>> print(dt.fields)
  4176. {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
  4177. """))
  4178. add_newdoc('numpy.core.multiarray', 'dtype', ('flags',
  4179. """
  4180. Bit-flags describing how this data type is to be interpreted.
  4181. Bit-masks are in `numpy.core.multiarray` as the constants
  4182. `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
  4183. `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
  4184. of these flags is in C-API documentation; they are largely useful
  4185. for user-defined data-types.
  4186. The following example demonstrates that operations on this particular
  4187. dtype requires Python C-API.
  4188. Examples
  4189. --------
  4190. >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
  4191. >>> x.flags
  4192. 16
  4193. >>> np.core.multiarray.NEEDS_PYAPI
  4194. 16
  4195. """))
  4196. add_newdoc('numpy.core.multiarray', 'dtype', ('hasobject',
  4197. """
  4198. Boolean indicating whether this dtype contains any reference-counted
  4199. objects in any fields or sub-dtypes.
  4200. Recall that what is actually in the ndarray memory representing
  4201. the Python object is the memory address of that object (a pointer).
  4202. Special handling may be required, and this attribute is useful for
  4203. distinguishing data types that may contain arbitrary Python objects
  4204. and data-types that won't.
  4205. """))
  4206. add_newdoc('numpy.core.multiarray', 'dtype', ('isbuiltin',
  4207. """
  4208. Integer indicating how this dtype relates to the built-in dtypes.
  4209. Read-only.
  4210. = ========================================================================
  4211. 0 if this is a structured array type, with fields
  4212. 1 if this is a dtype compiled into numpy (such as ints, floats etc)
  4213. 2 if the dtype is for a user-defined numpy type
  4214. A user-defined type uses the numpy C-API machinery to extend
  4215. numpy to handle a new array type. See
  4216. :ref:`user.user-defined-data-types` in the NumPy manual.
  4217. = ========================================================================
  4218. Examples
  4219. --------
  4220. >>> dt = np.dtype('i2')
  4221. >>> dt.isbuiltin
  4222. 1
  4223. >>> dt = np.dtype('f8')
  4224. >>> dt.isbuiltin
  4225. 1
  4226. >>> dt = np.dtype([('field1', 'f8')])
  4227. >>> dt.isbuiltin
  4228. 0
  4229. """))
  4230. add_newdoc('numpy.core.multiarray', 'dtype', ('isnative',
  4231. """
  4232. Boolean indicating whether the byte order of this dtype is native
  4233. to the platform.
  4234. """))
  4235. add_newdoc('numpy.core.multiarray', 'dtype', ('isalignedstruct',
  4236. """
  4237. Boolean indicating whether the dtype is a struct which maintains
  4238. field alignment. This flag is sticky, so when combining multiple
  4239. structs together, it is preserved and produces new dtypes which
  4240. are also aligned.
  4241. """))
  4242. add_newdoc('numpy.core.multiarray', 'dtype', ('itemsize',
  4243. """
  4244. The element size of this data-type object.
  4245. For 18 of the 21 types this number is fixed by the data-type.
  4246. For the flexible data-types, this number can be anything.
  4247. Examples
  4248. --------
  4249. >>> arr = np.array([[1, 2], [3, 4]])
  4250. >>> arr.dtype
  4251. dtype('int64')
  4252. >>> arr.itemsize
  4253. 8
  4254. >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
  4255. >>> dt.itemsize
  4256. 80
  4257. """))
  4258. add_newdoc('numpy.core.multiarray', 'dtype', ('kind',
  4259. """
  4260. A character code (one of 'biufcmMOSUV') identifying the general kind of data.
  4261. = ======================
  4262. b boolean
  4263. i signed integer
  4264. u unsigned integer
  4265. f floating-point
  4266. c complex floating-point
  4267. m timedelta
  4268. M datetime
  4269. O object
  4270. S (byte-)string
  4271. U Unicode
  4272. V void
  4273. = ======================
  4274. Examples
  4275. --------
  4276. >>> dt = np.dtype('i4')
  4277. >>> dt.kind
  4278. 'i'
  4279. >>> dt = np.dtype('f8')
  4280. >>> dt.kind
  4281. 'f'
  4282. >>> dt = np.dtype([('field1', 'f8')])
  4283. >>> dt.kind
  4284. 'V'
  4285. """))
  4286. add_newdoc('numpy.core.multiarray', 'dtype', ('metadata',
  4287. """
  4288. Either ``None`` or a readonly dictionary of metadata (mappingproxy).
  4289. The metadata field can be set using any dictionary at data-type
  4290. creation. NumPy currently has no uniform approach to propagating
  4291. metadata; although some array operations preserve it, there is no
  4292. guarantee that others will.
  4293. .. warning::
  4294. Although used in certain projects, this feature was long undocumented
  4295. and is not well supported. Some aspects of metadata propagation
  4296. are expected to change in the future.
  4297. Examples
  4298. --------
  4299. >>> dt = np.dtype(float, metadata={"key": "value"})
  4300. >>> dt.metadata["key"]
  4301. 'value'
  4302. >>> arr = np.array([1, 2, 3], dtype=dt)
  4303. >>> arr.dtype.metadata
  4304. mappingproxy({'key': 'value'})
  4305. Adding arrays with identical datatypes currently preserves the metadata:
  4306. >>> (arr + arr).dtype.metadata
  4307. mappingproxy({'key': 'value'})
  4308. But if the arrays have different dtype metadata, the metadata may be
  4309. dropped:
  4310. >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
  4311. >>> arr2 = np.array([3, 2, 1], dtype=dt2)
  4312. >>> (arr + arr2).dtype.metadata is None
  4313. True # The metadata field is cleared so None is returned
  4314. """))
  4315. add_newdoc('numpy.core.multiarray', 'dtype', ('name',
  4316. """
  4317. A bit-width name for this data-type.
  4318. Un-sized flexible data-type objects do not have this attribute.
  4319. Examples
  4320. --------
  4321. >>> x = np.dtype(float)
  4322. >>> x.name
  4323. 'float64'
  4324. >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
  4325. >>> x.name
  4326. 'void640'
  4327. """))
  4328. add_newdoc('numpy.core.multiarray', 'dtype', ('names',
  4329. """
  4330. Ordered list of field names, or ``None`` if there are no fields.
  4331. The names are ordered according to increasing byte offset. This can be
  4332. used, for example, to walk through all of the named fields in offset order.
  4333. Examples
  4334. --------
  4335. >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
  4336. >>> dt.names
  4337. ('name', 'grades')
  4338. """))
  4339. add_newdoc('numpy.core.multiarray', 'dtype', ('num',
  4340. """
  4341. A unique number for each of the 21 different built-in types.
  4342. These are roughly ordered from least-to-most precision.
  4343. Examples
  4344. --------
  4345. >>> dt = np.dtype(str)
  4346. >>> dt.num
  4347. 19
  4348. >>> dt = np.dtype(float)
  4349. >>> dt.num
  4350. 12
  4351. """))
  4352. add_newdoc('numpy.core.multiarray', 'dtype', ('shape',
  4353. """
  4354. Shape tuple of the sub-array if this data type describes a sub-array,
  4355. and ``()`` otherwise.
  4356. Examples
  4357. --------
  4358. >>> dt = np.dtype(('i4', 4))
  4359. >>> dt.shape
  4360. (4,)
  4361. >>> dt = np.dtype(('i4', (2, 3)))
  4362. >>> dt.shape
  4363. (2, 3)
  4364. """))
  4365. add_newdoc('numpy.core.multiarray', 'dtype', ('ndim',
  4366. """
  4367. Number of dimensions of the sub-array if this data type describes a
  4368. sub-array, and ``0`` otherwise.
  4369. .. versionadded:: 1.13.0
  4370. Examples
  4371. --------
  4372. >>> x = np.dtype(float)
  4373. >>> x.ndim
  4374. 0
  4375. >>> x = np.dtype((float, 8))
  4376. >>> x.ndim
  4377. 1
  4378. >>> x = np.dtype(('i4', (3, 4)))
  4379. >>> x.ndim
  4380. 2
  4381. """))
  4382. add_newdoc('numpy.core.multiarray', 'dtype', ('str',
  4383. """The array-protocol typestring of this data-type object."""))
  4384. add_newdoc('numpy.core.multiarray', 'dtype', ('subdtype',
  4385. """
  4386. Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
  4387. None otherwise.
  4388. The *shape* is the fixed shape of the sub-array described by this
  4389. data type, and *item_dtype* the data type of the array.
  4390. If a field whose dtype object has this attribute is retrieved,
  4391. then the extra dimensions implied by *shape* are tacked on to
  4392. the end of the retrieved array.
  4393. See Also
  4394. --------
  4395. dtype.base
  4396. Examples
  4397. --------
  4398. >>> x = numpy.dtype('8f')
  4399. >>> x.subdtype
  4400. (dtype('float32'), (8,))
  4401. >>> x = numpy.dtype('i2')
  4402. >>> x.subdtype
  4403. >>>
  4404. """))
  4405. add_newdoc('numpy.core.multiarray', 'dtype', ('base',
  4406. """
  4407. Returns dtype for the base element of the subarrays,
  4408. regardless of their dimension or shape.
  4409. See Also
  4410. --------
  4411. dtype.subdtype
  4412. Examples
  4413. --------
  4414. >>> x = numpy.dtype('8f')
  4415. >>> x.base
  4416. dtype('float32')
  4417. >>> x = numpy.dtype('i2')
  4418. >>> x.base
  4419. dtype('int16')
  4420. """))
  4421. add_newdoc('numpy.core.multiarray', 'dtype', ('type',
  4422. """The type object used to instantiate a scalar of this data-type."""))
  4423. ##############################################################################
  4424. #
  4425. # dtype methods
  4426. #
  4427. ##############################################################################
  4428. add_newdoc('numpy.core.multiarray', 'dtype', ('newbyteorder',
  4429. """
  4430. newbyteorder(new_order='S', /)
  4431. Return a new dtype with a different byte order.
  4432. Changes are also made in all fields and sub-arrays of the data type.
  4433. Parameters
  4434. ----------
  4435. new_order : string, optional
  4436. Byte order to force; a value from the byte order specifications
  4437. below. The default value ('S') results in swapping the current
  4438. byte order. `new_order` codes can be any of:
  4439. * 'S' - swap dtype from current to opposite endian
  4440. * {'<', 'little'} - little endian
  4441. * {'>', 'big'} - big endian
  4442. * '=' - native order
  4443. * {'|', 'I'} - ignore (no change to byte order)
  4444. Returns
  4445. -------
  4446. new_dtype : dtype
  4447. New dtype object with the given change to the byte order.
  4448. Notes
  4449. -----
  4450. Changes are also made in all fields and sub-arrays of the data type.
  4451. Examples
  4452. --------
  4453. >>> import sys
  4454. >>> sys_is_le = sys.byteorder == 'little'
  4455. >>> native_code = sys_is_le and '<' or '>'
  4456. >>> swapped_code = sys_is_le and '>' or '<'
  4457. >>> native_dt = np.dtype(native_code+'i2')
  4458. >>> swapped_dt = np.dtype(swapped_code+'i2')
  4459. >>> native_dt.newbyteorder('S') == swapped_dt
  4460. True
  4461. >>> native_dt.newbyteorder() == swapped_dt
  4462. True
  4463. >>> native_dt == swapped_dt.newbyteorder('S')
  4464. True
  4465. >>> native_dt == swapped_dt.newbyteorder('=')
  4466. True
  4467. >>> native_dt == swapped_dt.newbyteorder('N')
  4468. True
  4469. >>> native_dt == native_dt.newbyteorder('|')
  4470. True
  4471. >>> np.dtype('<i2') == native_dt.newbyteorder('<')
  4472. True
  4473. >>> np.dtype('<i2') == native_dt.newbyteorder('L')
  4474. True
  4475. >>> np.dtype('>i2') == native_dt.newbyteorder('>')
  4476. True
  4477. >>> np.dtype('>i2') == native_dt.newbyteorder('B')
  4478. True
  4479. """))
  4480. ##############################################################################
  4481. #
  4482. # Datetime-related Methods
  4483. #
  4484. ##############################################################################
  4485. add_newdoc('numpy.core.multiarray', 'busdaycalendar',
  4486. """
  4487. busdaycalendar(weekmask='1111100', holidays=None)
  4488. A business day calendar object that efficiently stores information
  4489. defining valid days for the busday family of functions.
  4490. The default valid days are Monday through Friday ("business days").
  4491. A busdaycalendar object can be specified with any set of weekly
  4492. valid days, plus an optional "holiday" dates that always will be invalid.
  4493. Once a busdaycalendar object is created, the weekmask and holidays
  4494. cannot be modified.
  4495. .. versionadded:: 1.7.0
  4496. Parameters
  4497. ----------
  4498. weekmask : str or array_like of bool, optional
  4499. A seven-element array indicating which of Monday through Sunday are
  4500. valid days. May be specified as a length-seven list or array, like
  4501. [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string
  4502. like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for
  4503. weekdays, optionally separated by white space. Valid abbreviations
  4504. are: Mon Tue Wed Thu Fri Sat Sun
  4505. holidays : array_like of datetime64[D], optional
  4506. An array of dates to consider as invalid dates, no matter which
  4507. weekday they fall upon. Holiday dates may be specified in any
  4508. order, and NaT (not-a-time) dates are ignored. This list is
  4509. saved in a normalized form that is suited for fast calculations
  4510. of valid days.
  4511. Returns
  4512. -------
  4513. out : busdaycalendar
  4514. A business day calendar object containing the specified
  4515. weekmask and holidays values.
  4516. See Also
  4517. --------
  4518. is_busday : Returns a boolean array indicating valid days.
  4519. busday_offset : Applies an offset counted in valid days.
  4520. busday_count : Counts how many valid days are in a half-open date range.
  4521. Attributes
  4522. ----------
  4523. Note: once a busdaycalendar object is created, you cannot modify the
  4524. weekmask or holidays. The attributes return copies of internal data.
  4525. weekmask : (copy) seven-element array of bool
  4526. holidays : (copy) sorted array of datetime64[D]
  4527. Examples
  4528. --------
  4529. >>> # Some important days in July
  4530. ... bdd = np.busdaycalendar(
  4531. ... holidays=['2011-07-01', '2011-07-04', '2011-07-17'])
  4532. >>> # Default is Monday to Friday weekdays
  4533. ... bdd.weekmask
  4534. array([ True, True, True, True, True, False, False])
  4535. >>> # Any holidays already on the weekend are removed
  4536. ... bdd.holidays
  4537. array(['2011-07-01', '2011-07-04'], dtype='datetime64[D]')
  4538. """)
  4539. add_newdoc('numpy.core.multiarray', 'busdaycalendar', ('weekmask',
  4540. """A copy of the seven-element boolean mask indicating valid days."""))
  4541. add_newdoc('numpy.core.multiarray', 'busdaycalendar', ('holidays',
  4542. """A copy of the holiday array indicating additional invalid days."""))
  4543. add_newdoc('numpy.core.multiarray', 'normalize_axis_index',
  4544. """
  4545. normalize_axis_index(axis, ndim, msg_prefix=None)
  4546. Normalizes an axis index, `axis`, such that is a valid positive index into
  4547. the shape of array with `ndim` dimensions. Raises an AxisError with an
  4548. appropriate message if this is not possible.
  4549. Used internally by all axis-checking logic.
  4550. .. versionadded:: 1.13.0
  4551. Parameters
  4552. ----------
  4553. axis : int
  4554. The un-normalized index of the axis. Can be negative
  4555. ndim : int
  4556. The number of dimensions of the array that `axis` should be normalized
  4557. against
  4558. msg_prefix : str
  4559. A prefix to put before the message, typically the name of the argument
  4560. Returns
  4561. -------
  4562. normalized_axis : int
  4563. The normalized axis index, such that `0 <= normalized_axis < ndim`
  4564. Raises
  4565. ------
  4566. AxisError
  4567. If the axis index is invalid, when `-ndim <= axis < ndim` is false.
  4568. Examples
  4569. --------
  4570. >>> normalize_axis_index(0, ndim=3)
  4571. 0
  4572. >>> normalize_axis_index(1, ndim=3)
  4573. 1
  4574. >>> normalize_axis_index(-1, ndim=3)
  4575. 2
  4576. >>> normalize_axis_index(3, ndim=3)
  4577. Traceback (most recent call last):
  4578. ...
  4579. AxisError: axis 3 is out of bounds for array of dimension 3
  4580. >>> normalize_axis_index(-4, ndim=3, msg_prefix='axes_arg')
  4581. Traceback (most recent call last):
  4582. ...
  4583. AxisError: axes_arg: axis -4 is out of bounds for array of dimension 3
  4584. """)
  4585. add_newdoc('numpy.core.multiarray', 'datetime_data',
  4586. """
  4587. datetime_data(dtype, /)
  4588. Get information about the step size of a date or time type.
  4589. The returned tuple can be passed as the second argument of `numpy.datetime64` and
  4590. `numpy.timedelta64`.
  4591. Parameters
  4592. ----------
  4593. dtype : dtype
  4594. The dtype object, which must be a `datetime64` or `timedelta64` type.
  4595. Returns
  4596. -------
  4597. unit : str
  4598. The :ref:`datetime unit <arrays.dtypes.dateunits>` on which this dtype
  4599. is based.
  4600. count : int
  4601. The number of base units in a step.
  4602. Examples
  4603. --------
  4604. >>> dt_25s = np.dtype('timedelta64[25s]')
  4605. >>> np.datetime_data(dt_25s)
  4606. ('s', 25)
  4607. >>> np.array(10, dt_25s).astype('timedelta64[s]')
  4608. array(250, dtype='timedelta64[s]')
  4609. The result can be used to construct a datetime that uses the same units
  4610. as a timedelta
  4611. >>> np.datetime64('2010', np.datetime_data(dt_25s))
  4612. numpy.datetime64('2010-01-01T00:00:00','25s')
  4613. """)
  4614. ##############################################################################
  4615. #
  4616. # Documentation for `generic` attributes and methods
  4617. #
  4618. ##############################################################################
  4619. add_newdoc('numpy.core.numerictypes', 'generic',
  4620. """
  4621. Base class for numpy scalar types.
  4622. Class from which most (all?) numpy scalar types are derived. For
  4623. consistency, exposes the same API as `ndarray`, despite many
  4624. consequent attributes being either "get-only," or completely irrelevant.
  4625. This is the class from which it is strongly suggested users should derive
  4626. custom scalar types.
  4627. """)
  4628. # Attributes
  4629. def refer_to_array_attribute(attr, method=True):
  4630. docstring = """
  4631. Scalar {} identical to the corresponding array attribute.
  4632. Please see `ndarray.{}`.
  4633. """
  4634. return attr, docstring.format("method" if method else "attribute", attr)
  4635. add_newdoc('numpy.core.numerictypes', 'generic',
  4636. refer_to_array_attribute('T', method=False))
  4637. add_newdoc('numpy.core.numerictypes', 'generic',
  4638. refer_to_array_attribute('base', method=False))
  4639. add_newdoc('numpy.core.numerictypes', 'generic', ('data',
  4640. """Pointer to start of data."""))
  4641. add_newdoc('numpy.core.numerictypes', 'generic', ('dtype',
  4642. """Get array data-descriptor."""))
  4643. add_newdoc('numpy.core.numerictypes', 'generic', ('flags',
  4644. """The integer value of flags."""))
  4645. add_newdoc('numpy.core.numerictypes', 'generic', ('flat',
  4646. """A 1-D view of the scalar."""))
  4647. add_newdoc('numpy.core.numerictypes', 'generic', ('imag',
  4648. """The imaginary part of the scalar."""))
  4649. add_newdoc('numpy.core.numerictypes', 'generic', ('itemsize',
  4650. """The length of one element in bytes."""))
  4651. add_newdoc('numpy.core.numerictypes', 'generic', ('nbytes',
  4652. """The length of the scalar in bytes."""))
  4653. add_newdoc('numpy.core.numerictypes', 'generic', ('ndim',
  4654. """The number of array dimensions."""))
  4655. add_newdoc('numpy.core.numerictypes', 'generic', ('real',
  4656. """The real part of the scalar."""))
  4657. add_newdoc('numpy.core.numerictypes', 'generic', ('shape',
  4658. """Tuple of array dimensions."""))
  4659. add_newdoc('numpy.core.numerictypes', 'generic', ('size',
  4660. """The number of elements in the gentype."""))
  4661. add_newdoc('numpy.core.numerictypes', 'generic', ('strides',
  4662. """Tuple of bytes steps in each dimension."""))
  4663. # Methods
  4664. add_newdoc('numpy.core.numerictypes', 'generic',
  4665. refer_to_array_attribute('all'))
  4666. add_newdoc('numpy.core.numerictypes', 'generic',
  4667. refer_to_array_attribute('any'))
  4668. add_newdoc('numpy.core.numerictypes', 'generic',
  4669. refer_to_array_attribute('argmax'))
  4670. add_newdoc('numpy.core.numerictypes', 'generic',
  4671. refer_to_array_attribute('argmin'))
  4672. add_newdoc('numpy.core.numerictypes', 'generic',
  4673. refer_to_array_attribute('argsort'))
  4674. add_newdoc('numpy.core.numerictypes', 'generic',
  4675. refer_to_array_attribute('astype'))
  4676. add_newdoc('numpy.core.numerictypes', 'generic',
  4677. refer_to_array_attribute('byteswap'))
  4678. add_newdoc('numpy.core.numerictypes', 'generic',
  4679. refer_to_array_attribute('choose'))
  4680. add_newdoc('numpy.core.numerictypes', 'generic',
  4681. refer_to_array_attribute('clip'))
  4682. add_newdoc('numpy.core.numerictypes', 'generic',
  4683. refer_to_array_attribute('compress'))
  4684. add_newdoc('numpy.core.numerictypes', 'generic',
  4685. refer_to_array_attribute('conjugate'))
  4686. add_newdoc('numpy.core.numerictypes', 'generic',
  4687. refer_to_array_attribute('copy'))
  4688. add_newdoc('numpy.core.numerictypes', 'generic',
  4689. refer_to_array_attribute('cumprod'))
  4690. add_newdoc('numpy.core.numerictypes', 'generic',
  4691. refer_to_array_attribute('cumsum'))
  4692. add_newdoc('numpy.core.numerictypes', 'generic',
  4693. refer_to_array_attribute('diagonal'))
  4694. add_newdoc('numpy.core.numerictypes', 'generic',
  4695. refer_to_array_attribute('dump'))
  4696. add_newdoc('numpy.core.numerictypes', 'generic',
  4697. refer_to_array_attribute('dumps'))
  4698. add_newdoc('numpy.core.numerictypes', 'generic',
  4699. refer_to_array_attribute('fill'))
  4700. add_newdoc('numpy.core.numerictypes', 'generic',
  4701. refer_to_array_attribute('flatten'))
  4702. add_newdoc('numpy.core.numerictypes', 'generic',
  4703. refer_to_array_attribute('getfield'))
  4704. add_newdoc('numpy.core.numerictypes', 'generic',
  4705. refer_to_array_attribute('item'))
  4706. add_newdoc('numpy.core.numerictypes', 'generic',
  4707. refer_to_array_attribute('itemset'))
  4708. add_newdoc('numpy.core.numerictypes', 'generic',
  4709. refer_to_array_attribute('max'))
  4710. add_newdoc('numpy.core.numerictypes', 'generic',
  4711. refer_to_array_attribute('mean'))
  4712. add_newdoc('numpy.core.numerictypes', 'generic',
  4713. refer_to_array_attribute('min'))
  4714. add_newdoc('numpy.core.numerictypes', 'generic', ('newbyteorder',
  4715. """
  4716. newbyteorder(new_order='S', /)
  4717. Return a new `dtype` with a different byte order.
  4718. Changes are also made in all fields and sub-arrays of the data type.
  4719. The `new_order` code can be any from the following:
  4720. * 'S' - swap dtype from current to opposite endian
  4721. * {'<', 'little'} - little endian
  4722. * {'>', 'big'} - big endian
  4723. * '=' - native order
  4724. * {'|', 'I'} - ignore (no change to byte order)
  4725. Parameters
  4726. ----------
  4727. new_order : str, optional
  4728. Byte order to force; a value from the byte order specifications
  4729. above. The default value ('S') results in swapping the current
  4730. byte order.
  4731. Returns
  4732. -------
  4733. new_dtype : dtype
  4734. New `dtype` object with the given change to the byte order.
  4735. """))
  4736. add_newdoc('numpy.core.numerictypes', 'generic',
  4737. refer_to_array_attribute('nonzero'))
  4738. add_newdoc('numpy.core.numerictypes', 'generic',
  4739. refer_to_array_attribute('prod'))
  4740. add_newdoc('numpy.core.numerictypes', 'generic',
  4741. refer_to_array_attribute('ptp'))
  4742. add_newdoc('numpy.core.numerictypes', 'generic',
  4743. refer_to_array_attribute('put'))
  4744. add_newdoc('numpy.core.numerictypes', 'generic',
  4745. refer_to_array_attribute('ravel'))
  4746. add_newdoc('numpy.core.numerictypes', 'generic',
  4747. refer_to_array_attribute('repeat'))
  4748. add_newdoc('numpy.core.numerictypes', 'generic',
  4749. refer_to_array_attribute('reshape'))
  4750. add_newdoc('numpy.core.numerictypes', 'generic',
  4751. refer_to_array_attribute('resize'))
  4752. add_newdoc('numpy.core.numerictypes', 'generic',
  4753. refer_to_array_attribute('round'))
  4754. add_newdoc('numpy.core.numerictypes', 'generic',
  4755. refer_to_array_attribute('searchsorted'))
  4756. add_newdoc('numpy.core.numerictypes', 'generic',
  4757. refer_to_array_attribute('setfield'))
  4758. add_newdoc('numpy.core.numerictypes', 'generic',
  4759. refer_to_array_attribute('setflags'))
  4760. add_newdoc('numpy.core.numerictypes', 'generic',
  4761. refer_to_array_attribute('sort'))
  4762. add_newdoc('numpy.core.numerictypes', 'generic',
  4763. refer_to_array_attribute('squeeze'))
  4764. add_newdoc('numpy.core.numerictypes', 'generic',
  4765. refer_to_array_attribute('std'))
  4766. add_newdoc('numpy.core.numerictypes', 'generic',
  4767. refer_to_array_attribute('sum'))
  4768. add_newdoc('numpy.core.numerictypes', 'generic',
  4769. refer_to_array_attribute('swapaxes'))
  4770. add_newdoc('numpy.core.numerictypes', 'generic',
  4771. refer_to_array_attribute('take'))
  4772. add_newdoc('numpy.core.numerictypes', 'generic',
  4773. refer_to_array_attribute('tofile'))
  4774. add_newdoc('numpy.core.numerictypes', 'generic',
  4775. refer_to_array_attribute('tolist'))
  4776. add_newdoc('numpy.core.numerictypes', 'generic',
  4777. refer_to_array_attribute('tostring'))
  4778. add_newdoc('numpy.core.numerictypes', 'generic',
  4779. refer_to_array_attribute('trace'))
  4780. add_newdoc('numpy.core.numerictypes', 'generic',
  4781. refer_to_array_attribute('transpose'))
  4782. add_newdoc('numpy.core.numerictypes', 'generic',
  4783. refer_to_array_attribute('var'))
  4784. add_newdoc('numpy.core.numerictypes', 'generic',
  4785. refer_to_array_attribute('view'))
  4786. ##############################################################################
  4787. #
  4788. # Documentation for scalar type abstract base classes in type hierarchy
  4789. #
  4790. ##############################################################################
  4791. add_newdoc('numpy.core.numerictypes', 'number',
  4792. """
  4793. Abstract base class of all numeric scalar types.
  4794. """)
  4795. add_newdoc('numpy.core.numerictypes', 'integer',
  4796. """
  4797. Abstract base class of all integer scalar types.
  4798. """)
  4799. add_newdoc('numpy.core.numerictypes', 'signedinteger',
  4800. """
  4801. Abstract base class of all signed integer scalar types.
  4802. """)
  4803. add_newdoc('numpy.core.numerictypes', 'unsignedinteger',
  4804. """
  4805. Abstract base class of all unsigned integer scalar types.
  4806. """)
  4807. add_newdoc('numpy.core.numerictypes', 'inexact',
  4808. """
  4809. Abstract base class of all numeric scalar types with a (potentially)
  4810. inexact representation of the values in its range, such as
  4811. floating-point numbers.
  4812. """)
  4813. add_newdoc('numpy.core.numerictypes', 'floating',
  4814. """
  4815. Abstract base class of all floating-point scalar types.
  4816. """)
  4817. add_newdoc('numpy.core.numerictypes', 'complexfloating',
  4818. """
  4819. Abstract base class of all complex number scalar types that are made up of
  4820. floating-point numbers.
  4821. """)
  4822. add_newdoc('numpy.core.numerictypes', 'flexible',
  4823. """
  4824. Abstract base class of all scalar types without predefined length.
  4825. The actual size of these types depends on the specific `np.dtype`
  4826. instantiation.
  4827. """)
  4828. add_newdoc('numpy.core.numerictypes', 'character',
  4829. """
  4830. Abstract base class of all character string scalar types.
  4831. """)