You are on page 1of 26
. | Q SANTOSH RUNGTA GROUP OF INSTITUTIONS @® | Untt.2 2 The Numpy Mbrary ‘Mumps © Numpy os @ python Silsroxy aused pot worcing with avuays. e 9t oko hos functions for avoaing dn domain af Limeor algelsro 5 Yount anuyoum, and. © -madstees 0 Numpy stands {or Numuical Python. Mrstauation of NumPy Drstaw tk suing this command » : : i Aigh j< The tmportance aumpy ts the farmoqenoud 9 poriane ah eee ana} bjeck. + Dako Manipulodion iv python. vk nearly. equivarent 2o the amantputation, of eT CO te eNdarrouy us the n-dimensional arr objects definack in the mumpy which stoses Lhe cotection of the vfmilor ype of goment. Tn ether woide we can Aefine .o dor 0% the eotlecion. af the data. type (dtype) objeck | othe mdarray object car be accessed uring the O based, indexing. Each element of- the Mray. object contains the 4ame vize im the Core 8 Are aoc class tv Numpy away wi called as ndawray arrays ave acceme by. nd squue te ® Frements in Num pp py thon brackets and can be initiatized by duing wes tak. Canating os ndorrray. objects im port nee as np = NP array print (a) fvoy Creation Thue ave Vorious Ways +0 oredke arraus tr KlumePy . Ae Regular o for Example, you: con oer ONL AH thon List we kuple Laing the away function +The type the reswting curuy. fh deduce, tho type the Cement tha “eequance, i 7 o offen, the elements an aio. POL origt AUUKN Ouny tut ib afte of pic lt Hence , NumnPy. siemens, functions bo ereaee arrays With tnitiar placeholder, coreent 3 * Orange: Anuins Wenly spaced vouuls within a guen [nkenal. step ste vs" specified Q SANTOSH RUNGTA GROUP OF INSTITUTIONS ° Reshaping reauy ¢ We con use AWShape mithod to Aeshape an © PLOT Aros We con. Ube amithod. 40 get Q Lo "4 o{ orwroy, cotlnsbed. pnw dimension. Pd Creaking me dimentional trport MUMPK Os LP wust= [100, 200, 300/200] v= np + array. (Lint > pani cn) Output ¢ [too 200 300 400] tr, NuuMpy = Finding, sha, Alaris of he fay? she Array. traport nummy ab Mp arr= np+ array CLL 472) 3/44, C415, 6,7 J, [9,101,237]) print (am ndim) pant (avy) qwsputs a Ele ase A) bus e to WSs to 1 93,9) »BHLA CAMPUS: Rng Escalona Campus, Koka Road, Kurud The nden fonctions cow be wed. to Find the dimenston oj a >> RAIPUR CAMPUS : Rungta Educational Campus, Near Nandon Van Finding the sito of each array element >— The ikem stze tom us wsed to get the Jf72 of each, UO, iter. « t artusns the numbu ci bylts saren by Example ¢ impost TUL py Os UP ae Trizay) PrINE (“Each tem contains’, a.ctemstze » “by kes) Qulputs Coch em vontains & bytes Finding the dota, type of each arroup Lem: — %o chock the dato type ef each asnay- tem , the dty pe function u's ued. « Example 2 impoat mum py O4 VP = np-array ( [01,23] 1) Print (“Badr them us of the typel, a-diype) ue Luts Foch tem ts Of the type ente4y Finding the shape and site ©] He Orrway + Ereport wuPY. Os HP Qe Mp array. (04,2) 34,8764 up) print (“Pty size”, astzo ) pring( «shape 2", a.shape ) OUP UALS Avroy Sizes 7 auabov CHA q SANTOSH RUNGTA GROUP OF INSTITUTIONS feshaping, Ae oray: objects ¢ The xeshapeO function anotaked with the ndaw object ots aed to aeshape the anay 94 accepts the Luso pararneltr ‘mdicoting the wow and. columns of are row shape of the, Jd 7 sealke —_———— (eae 5 ah [As te 2X3 3x2 Examples Tmpost numpy as Oe wh arog (LC 2] 08/4) /05 16] J) ees o ee ad. ° 7 a=a-rsuhope (2/3) fi print (“printing the reshape anay.. ..") print(a) “ ia gueput-= Printing the erigival ASAD [Lt 21 [34] ts eqj ; Painting tha wshaped ONY. lien | Testa Cee) a] > BHILAI CAMPUS : Rungta Educational Campus, Kohka Road, Kurud Ph, despace dhe tena spa.ce L) fumce’on. euduuns the eV Spaced, values over tha, giver, jntowal TAL folowing examplt Altus the LO ean Axpenaed. vols over the given interval 5-15 Fromple s tmpoxt uumpy Ae np Q=np- Linaspace{ 5; 15/10) print (a) Queput + (eee GNU 722929299 9, 2333.3333 3.44yy yNyY 10+ 55555556 tl 66666667 amp _Rorouy t — A NumPy -muttt—dimensional array us rapreented by the Qous Whar oxte-0 Jepausennes the solumy ancl anti - 4 Mpurnis the rows. we can. mention the Oud to peafoum pout ® column Level coteutottons tke the addition of ROU oy column element axis 0 len mas( eh agar : 1277777779 13. 88eeesed IS. J @ SANTOSH RUNGTA GROUP OF INSTITUTIONS ® oa ae ax np 0. wep erry CC 2150) fio, 15/4) paint (“The arway 2", a) ’ pint (‘The maximum element Sol ‘wa omar (avés=o)) pant («the minimum edement of Apts 7 erin (axts=4)) print (the qu af Al rows! oe swrr(axts=4)) OaLkput ¢ The arvay lente [ios 47 The maxtmum elements 6 columns [10 15 307 The minimum elements & vowWS [1 4] The sum of wows [a3 24] Baste_opevaktons ¢ 4. Operations on single we £On we overloaded axtihmetic eperatow to do elemen& we operation on to Hoole a NW Ara -In cor Ee opevarors, che ern. psa. Le modified Bramples tmport mumpy as YP O= npc arvoip (le 125/33) paint (“Adding 1 to eveup elemones", a+! ) nt Ce Suwbt 3 each element:”,a-3) print mutttplying each. etemente by 104, qx!0) a Educational Campus, fan Van pubputs Adding 4. to vey coment? 1 23 6 YT Subtracting 3 rach Ulm » [2-12 07 Muuttplying each element by 10: (10 20 50 307 3h Opeworkoas : ‘Those operations Apply an elemontuuse and a neo us created «'Yourean we at basi crtthmeb’e operators Auer boils et K ° sala vumpy. as Wp Om Mp. oman EC), 21,1 8411) bs Bae! CL(4 3], [2,4 aa aa A sum 2\n, +b) pie all mutton a\n", ak ) print matafk amt plication 2\n", a--dot(b)) (utpues Arw sums, [c5 5 [551] Pow amit plicastor ‘o Cla 6] Lead] Moist muuttpiicoion = Tees bel [20 1a]] q SANTOSH RUNGTA GROUP OF INSTITUTIONS @) Indexing § gra hase of Moy indexing ai tmportant analysing and. manipwating thre aywuuy object > NumPy offees ay ways to do 25ND, indexing. 6 oe ust Wike ists im python » Nu arrays can be sud AS con be steed muutidtmmntonal, yor need. 40 specisy aula, for 20ch. dimension of tho dnawing ° Integer rrr indexing : Tn this method, Lat cre panied fo Jndextrrg. of cossesponiding oubitou, asnray , Boolean away Indextngs thts method us vsed whin We pant Jo pik ion fom aay whith satisfy Some condition. each dimension.» one to one appt element us done to Lonstuck & Ver e Example: Ymport vwumpy as np are Mpeawoy( [L-1,2, 0, 4 Ele L4,-0°5 620), L2-6,0/4/84 , [3,-t,4,xv01) 4 gun aro’ aa See a ‘) ; nt (Rar sth ut 2 Aows ancl alternae P Og tt Mr COA DOE ND tem PD rd 4 roger ermey trdeing example temp = ave(Lo,1,2,3),L3,2,1,0]] print (\n Element at indices (0/3), (1,2) (2/1 )" " (310): \n”, temp) # boolean array ercley example und. = ar yo a temp = avy [cond] Print ("\n. Eloment greate, than 62\n", emp 2 Outputs Arrays with flut 2 rows and allemate oslurnns(o and2)- [[-1. 0-9 [4- G. J Elements ot indices (0/3) ,(1)2) ¢ C21) ,(3)0) ¢ [Mc G Go Sy) Eumenta grease than O: CC Aen8h 3. 4. 2. Dato. Type Eve nds has an associared data ype (dtype) object « Ths ee objec (type) 4 We site e layout eee cara Aves wis infetmation, about ¢ Tupe of the dasa ( f > Python objec ee) ype of (tn uber byw | Byte ordas of the date, @ SANTOSH RUNGTA GROUP OF INSTITUTIONS (j)) Lmpost ruumpy at hp di = np. aty pe (tata pring (Byte ovdar ub. de. byte ordes ) print (size is 3 db «item Size) print Ctpata type ui, dt-name) ute Byte ovdu ua > Stl ub 34 Name of dota 2ype us : int 32 Num?y amray eevattove s — a srerotoy objects ee» ndibe whith can be Na TS ER i thon standard vied “to teevake over the guru ano wing. py tltvatoy Onterfore- Examples cmport: uxt (object) Shape Maniputotion Shape Manipulation vi a sechmigue by which we cow manipylote Khe shase of TUMPY OrwOLYs anol then convect- the crrray. ito arwrauy 4 matrix "4 req utred Shape Qn Seen onrepaptoer a tnprstind ent pe Bor ALB HD import mumpy as Np awe np-random -randomlis)) print (an? N= Cate pechape (3) 5) ee oR ye np-amay( £1,213) 4595 Lo 1/8/9110) J) Le ye neshape (2) 5) = Ke vovelc) paint (a) Q SANTOSH RUNGTA GROUP OF INSTITUTIONS BROADCASTING: o the sum Bruradcasting nets Ae chow numpy dreaks arr sith Diposne Dimension Busing Avdithme2ic operations whith toad to codon constraints, the amallex Oma Ls broadcast rey the Loiger ho that have fsmpoathle. Shapes. iad cd © Booadcosth tds 7% Alias, a mean ef vectorial Orray operation. setbaaas ws } aeons Jen. Uae nied, we dinow that NuumPy irnplemented inc, Examples tempor uumpy 4 np a=np- ama ([5)7,3,4D benp away C [90 80,030) C=O*b print (ec) Broad.costing- Rules . 1. Broadcasting #0 DHHS Hogethux follows Hhose yuleg g gy the orouys dort ove the game hank then prepend, the shape the Lowes Aank LUA. with 1s wntil both Shapes haves the Same songth . > BHILA! CAMPUS :Rungta Educational Campus, Koha Road, Kurud __> RAIPUR CAMPUS : Rungta Educational amp. dan Van ReThe two Quiays AL 4 rave the dame dixe dn the dimension vy if NL ef the asaus Aas aie 4 im that dimension. compatible Ma dimension if th S.the quays can be busadcast togethin 4§ they O12 coTmpartble. jotth cull dimension. dye AFL broadcasting » cach, art behaves ax 4 it had shape equal b> the eLenrnt-wwtse BOLOx Lara shapes sj the two Soop AHAYS « ‘ B TM any dimension phtre one aw had sie 4 amd the ord others Daay dad Atze 4 than ds the Jule age behouts Os Y dk ware sopied along nat mension. Examplel: Stngte Dimension array Empoxt tuumpy as np a=—np-amayx ( [14,0 ,19 ) print (a) b= 3 point Cb) C= atb print (c) fit. 13 J 2 [2014 22) Q SANTOSH RUNGTA GROUP OF INSTITUTIONS Fxample2® 2-D OHXay Impoue wumpy ax np R= np- array, CL rt) 22/335, (10,20, 30J J) print (A) b=4H print (b) c=A+b print (c) Outputs [eat 22 33) Lto 20 30) 5 [cis ae 34] Ciy 24 343] plotting a Avo dimenstonad functors Neaienines us abe Jeave wed 3 lis ine, t Based. on an eae Pca Ys we ens ea O function z= f(%4) € les tes Erampre pe atpieit pyfiot 04 ple x= np avange (0, 3*npepts 0 “p Yy -stn =npeStn(x) YH = ae wos (x) Road, Kuru Cae Plt plot (X2 y-cos ple extabel.(*x dowd rabel' ) Pls ytobUCey ani abel”) tel Coste : phen a eee Te sene? , eosin’) — sine sine = taste O15 Y anuj lab Ss & - Zo 4 ¢ Karn ober Numty, fines igee ond Matrix Function s— NumPy hos Seperate amdule for Linear augebya, «The module veonkoins all sre functions Misa, Uineor 0g om crumpy ettnalg, ds she package Jn Numfy for ae Ainoas, Pulgebvo.- dimwor Aigebsra, us ue branch cH amatnenah?c concerned votth vector Space and. ‘mapping amongs the Spots. ———————— @ SANTOSH RUNGTA GROUP OF INSTITUTIONS @) ides the i tons £0 perform the a + ee Stina impute dota. Sno Function Definition 94 ds wed to potoulake the doe de tC) de produce of wd OMA . as vdotl) 94 ots used to podewerte the dot product of ww vedar - So ‘ins Ob ub awed bo cotuvake the domes product a fd - QUAYS. Bt ie wued to coLutoke the ho anvatmull) Maine orm wuLetpiceatcon ° fi be dat 0) Gb da sed to colutore thro dareuminane oO y a golve () DE ub waed to Solve the Leneas s emadrix equodton « AS tnyC) gt vis vsed to calculole tho x aut plecative mmveLee ef the numpy -dotl) Uton :— : Thi puncton Us dued to MHD ine dot eens ‘a the two anobAtees. 94 us Bimulor to the matt MULLET ULLAHEON Examples tmport, “Mum Y On np O=np- array (TT 100, 200) 123,121 benp- array ([C 10/20], Li2, 210) dot= npedot (a5) print Cot) outputs [[3400 6200] err eet Oe) suurmpy -vdlot () the ve auton 3— netton uk are to cotuuate the Cee fares two o§t con be defined 114 the ee 4 produ Gi a eloment’ 4 amuudt -dimensiore. ee : Example: tmport: umpYy as Np ha Se (TLt00/260, £2. 3/127) alt Lto,201, Vow ae oy pei print (vdot) Gukputs 5328 umpy stars () fancttons— Tha com Aetny the dum the product- of trnte Smee, Shr tat ouney » Foy “ -climorsional st autuunk the sum 2 Ahe product ef elemamt-— over tre Lave outs « of Ae produc of q SANTOSH RUNGTA GROUP OF INSTITUTIONS ® Example, SE ren ox of o=nprostoy. ( (112, 3)4/5161 b= np-arnray ((.23,23,12) 2/12) tenes = mpotriner (asb) yovnt Cinna) Output: 30 mumpy mat MUO) function s Bt vs ued to Attn the moun paar” Ot gb atvehy OF enor if the shape af bet aligned fo emuterplicatton + the hwo matrcces, amadaces Jk met Examplez Tmpore murmpy as np a=np-arwray ([61,2,31, [4/51 6). C1, 8 3) be np -ovvray(CL 23, 23/12] . 2/20/07 8/9) “UL = np-motmut Carb) print (raul) Nump debuminane em the madix can be coteutared ag tie the ae etormonts. She detuminart Of wut cx fouowing 2x mare hy C=D Lon be caleuloled of AD—BC , HILAL CAMPUS : Runge Eaucationl Campus, Koha Roa, Kurd a. Example: Jimpost muumpy as np a=np- oro ((F 1,27 [3/4 I) print (np. Jinalg. det (a)) Ouukputs —2 +0000000000000004 Peery eunvaug: solve CY funceions dhs functton us sued to solve Ce quadsatic equatton whore Values cam be gwen an the qoum cae the Mattix Example * fmport- Tum py as mp a=np-asray( £01 ,29,[3,4I)) bemp- C(l12I, (31471) print (np dinaly. sve Casb)) ouput ii oD ome) @ SANTOSH RUNGTA GROUP OF INSTITUTIONS @® Nectosteostton ¢ © Vecloxtnation uk 2 dechmique of implernanting AsAdU Optacsarons deithouke using. jot Apops « Onstiad, wt use functions efinach by vartous anodes ushich ore highty optemized thet peducs the gunning andl execution terne of code. © Vectortsed operation. will be fase4 Ahan thelr pure Python equivalents swith the biggut jropack im any oy a ea ane flower shan their C/err fount pare. tython. Js an imeupuled Lonquoge and. meth xf te te implementation, fh dow Ihe main reason for this 4 toon comes own to the mit MaLUAL pyehen and lack a com pur Aovel optimicalt on. whedy antur MLN overhonds + NumPy. beimg 2 C Emplementatien of ois 3 Python. Providls vettorized action on Nuump y DHLU0 Bramplels vistrey vectored Lum smuthed. on Num ‘ we wall ans the vetiorized 4m. method mds with dimple ron -vertortard. operation - tee the ievateve emuthod to colaate the eum oe sruumbers from ae Tmpost mumpy a6 Np tenpox dimeit- paint (vnp- sum (np- arange (15000))) print (time taken by vectorized unre”, end=’ “dD % temeit npesum (Mp- avange (15000) ) total =0 for item. tre range (.0,15000)°. fotal= elem Q =total pant U\n" + str(a)) Print («Teme taken by Terative sume ", end= " ") fo beet OL Qudpul”s 1249 2500 [ Teme taken. by yettorised sums $209 US tI-RE lus pey Lop 112492500 Tae ee. by Uerative sume 221 ns £ 4-38 ns per lowp o She above Example Shows the more optimal Nedure of Vectoatzed operations of Hern when (ormpared votth ann —Vectoi feed operators « © The moans when cmpntational e cb uh the in Oo progam dnd sve eae sing ¢ Ahese offre opuations vathe we should pee Numb vertortzed function - e @j SANTOSH RUNGTA GROUP OF INSTITUTIONS ® Vectoatcatton Exomple 2+ Impost Tumpy as np from kime import time n= 100000 X= np random rand (4) Yenp:tandsme yand cn) print (1) print C4) Stat time = time 0) ee fox K in ange (mn): Li. append. (% [x] + yx) end Hime = fime C > print (end-time) print (Stark time ) timed = end time — stat - tte paint (timed) gueputt [0.03 216656 0244358 291 -----+ 013 55851 82 08534361] [o-12.80503! 056469998 ---+ 061992892 0+ 21475963] 166 G5 tuo 1356 169 1666 157410" 02626 9 1 6 (094 016633453365 | Educational Campus, Kohka Road, Kurud > RAIPUR CAMPUS : Rungta Educational Campus, Near Nandan Von @ SANTOSH RUNGTA GROUP OF INSTITUTIONS @ Sisuchured omauts & a, gran do dtuut En C. 94 ub 9 ‘Nuumpy’s gyauctured Luts similor to & wi used for Arouping dato Pf diye: types sound. aize okt uclune aria nes data container called fields - Each, dodo pied. con contain data af ony aype pnd size - eh con be acceded. with “the Aetp f dot Notation. Note+ with named pie that con contain data ef Various +4 pes and AttA. Properties of staurluredt fea s— o AU dhucs have dame number °f fields . © All dimes have ar yu NOM, for Fxample, comidn a Reemicnited: aC Atudemt achich hos dipaant fields Mee Mame 5 Yor pyres Student Ear — Prajakia Oyen — fowth, oaks ——T66 44 6k 55 > BHILAI CAMPUS ; Rungta Educational Campus, Kohka Road, Kurud = > RAIPUR CAMPUS :Rungta Educational Campus, Near Nandan Van Each accord dm OAc Student fros a serudure of clas Abu. The Anny Of Ste ut siferreol An OA stauct Ob addi any. Now Reds for Oo OW eck Jin the anrcu , torntains the a msey Examples Umpork uLMpy Os np O= Mp: array ( L (sana, 2 / 21-0), Cemanss’, 1, 29-0) 1 dtype= [Cename?, (np-st— 10) (fage?,np-nt 39) C'wseight?, "ap. float 64)']) patnt (a) outputs [C'sana’,2 ; 21.6) (emanst! 7, 2900) ] Exampled: dhe dtuneeure anray can be sored by vst TUPY sort) Method and. “pursing the odor ds Pee Shs POLAT LAKLAs the vaLuUt ef the fd according to which JE us mooded to be sorted , Fnpoat apy 4 Q= np- array ( T (eganc’,2.2-D) (Manse, 1, 2960) J, dbype =[(enome, (mpesta— 5 10Y) »('a92,np int an), (wodight! npeftoat 64) ) benp- sort (a , prdu=enams? ) ee Dee sti accorduip ty che name', b) Q SANTOSH RUNGTA GROUP OF INSTITUTIONS @) Output souttng, according bo the name [ (emanst’, 7 5 29°) (sana} 2,210}

You might also like