_add_newdocs.py 204 KB

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