_add_newdocs.py 198 KB

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