You are on page 1of 14
~ INC492: Introduction to Data Science Week02 - Python for Data Science Dr Teema Leangarun Department of Controls System and Instrumentation Engineering Faculty of Engineering, KMUTT Student name: Tanatad Seakow ‘Student 10: 64070504007 ~ NumPy Exercises Now that wee leamed about NumPy lets test your knowledge. Wel start off wth afew simple task, and then youl be asked some more complicated questions > Exercise 1 ‘create a program that etums True when all elements passed tothe array ate Tue. Given array: fared = (22,91455,6.7.80,28) ard © (052.2,214,5,6,768,9,38) Note: npall Isa function that returns True when all elements of ndarray passed to the fist parameter are True, and returns False otherwise, fiaport nunpy Libraries and nane it to be np. eport nunpy a5 0 dared = (3,2,34,546,7,8,9,20] area = [0,2,2,3,445,6,7,8,9,18) print (arr) print(are2) 5,6, 7, & 9 201 2.5, 6. 7, 8 8 108) np. al(are2) print(all_trus) print ~ Exercise 2 Create & program that returns True when any of the elements passed tothe array are True. Let arnt = [10011 (000.0) Note: np.any() is @ function that returns Tue when any of the elements of ndartay passed to the first parameter are True, and returns False otherwise, ara ‘import runpy Libraries and nane it to be mp. Seport runpy as 6 fereate two array ared = (2, 8, 8, 1) arr2 = (0, 8, 0, 6] ‘téisplay original array print(arra) print(arr2) [a 8, 8, ay Te, 8, 6, 8] “acheck any of the elements passed to the array are True and display result nport nunpy 35 0p fer chock_any_trve(rr: return np.any(arr) print("area has any True elenents:", check any_true(arrt)) Print(*are2 has any True elenents:", ehece_any_true(arr2)) are has any True elenents: true {re2 has any True elenents: False + Exercise 3 (check if values of an array in Numpy ate complex, real or scalar ‘import nunpy Libraries and mane 1t to be mp. fmport money 6p fereate nunpy array that contain complex unter array = np.array(Td + 25, 3.8, 4, 5 + 6}, 7, 8.5, 9,33)) satspioy ontginal array print (arrays) [A253 20 4 o0d 5. 48d 7. 48.5 B.5ees 9, 20.5 93. 0.1] check complex complex array = np. sconplex(array3) 4 Display the array of True or False values print (complex srray) [ Teue False False True False False False False] feheck real real_array = rp.isresl (arrays) ‘Display the array of True oF False values for real nurters print(reat_array) [raise true True False True True True True] feheck scalar sealor_srray = np. ssealar(orray3) print (scalar_srray) raise ~ Exercise 4 {create a program to show the greater, greater_equal less and less equal comparison of the elements of two arrays ‘ieport nunpy Libraries and mane 18 to be mp Anport nunpy 35 ‘ereate numpy array to show >, >01 array2 print("Greater than :*, greater than) Greater than : [False False True False True) requal = array >= array2 print(“Greater than,equal :", greater_equal) Greater thanequal + [False False True False True] less_than = arrayt ¢ array pring("iess than’ =, Tess_than) fess than: [ True True False True False) ess_equal « arrayt < array print(*less than, equal :", less equal) ess than, equal + [ True True False True False) Exercise 5 Checks two array whether they are equal ané equal intolerance. Given aray ares = (8,20,38,40,58,40,-28, 200) area = (8,20,38,40,58,-40,-20, 298.92) inport nunpy Libraries and mane it to be mp. nport nunpy 35 0p arr = nprarray({3®, 28, 38, 48, 58, -4@, -18, 200]) area = nplarray((1®, 28, 38, 48, 58, -48, -18, 200,002)) saispiay ontginal srray print(arra) print(arr2) [28 20 30 49 50-49 -30 260) [48.20.38 aa. se, ae, e,—200.002) check the equality foul = art se arr? print (equal) [teve true true rue True True true False] fcheck the equality within a tolerance Ssntoteranee = rp.allclose(errt, arr2, atol-tolerance) print(artolerance) Exercise 6 Find out the memory size of @ numpy atray and Create a 5x5 aay of zeros, ones and &s inport nunpy Libraries and mane it to be mp. Snport nunpy 35 0p Q61 Find out the memory size of a numpy array fereate nunpy array for 18 numbers (you can put any nunber) arenen = ep-array((8, 234, 35, 496, 53, 63, 7, 633, 9,5)) saisplay original array print arene) [29236 98 476 536 70 8 5) check nenory size of array enory_size = arrnen.obytes print( nonory_size, "bytes") a9 bytes 62 (create a SxS array of zeros, ones and Ss fereate array zeros eros_seray = np.zeros((S, §)) saisplay result print (2eros_rray) 1 8.8. 8] eee] eee] ea el fereate array ones fones_array = np.ones((S, 5)) sasspiay resutt print(ones_array) (a. ica a i a fours_array = np.full((S, 5), 5) print fours_array) L L [ [ t Exercise 7 Finda solution in Nurnpy that generate random numbers based on standard normal cstribution In this exerciee, we ate going to generate random number up-to 20 based on standard normal dstibution. Note: normal(loc=0.0, scale=1.0, size=None). Draw random samples from a normal (Gaussian) distribution. The probability density function ofthe ‘normal distribution, frst derived by De Moivre and 200 years later by both Gauss and Laplace independently. inport nunpy Libraries and mane it to be mp. randon-runbers = nperandom normal (st20=20) saispoy result print(randon_runbers) [-0.20951337 -0.se001959 -0.sze12si8 0.sois9651 @.1874619 0.28486242 4.2s273508 0,38857725] Exercise 8 Print a vector in numpy ranging from 10 to 50 skipping the ist and the last values and print the est of them. sioport ntapy Libraries and nane it to be np. nport nunpy 35 np feneate nunpy array vector = nparange(28, 58) print(veetor) [19 a1 a2 23 16 25 a6 27 a8 19 20 21 22:23 24 25 26 27 28 29 30 31:32:33 434 35 36 37 38 3940 42 42 42 44 4S 46 47 48 43] saispiay array print (vector[ 3 » [an 22 13 24 a5 26 a7 a8 29 20 22 22 23 24 25 26 27 28 29 30 3132334 Exercise 9 Use a for loop over an array and print each element of the array separately. Challenge: You can use for loop for 1 times and Do not use reshape() function ‘Given array W246 oe 3, 22, 18,38, 35, 26, 27, 28, 19), 2, 22, 23, 24, 25, 26, 27, 28, 29), BL, 32, 98, 34, 38, 36, 97, 38, 38), 1, 2, A 85, 45, 0, 48, 487) Hint: npnaiter fieport nunpy Libraries and nane 18 to Be mp nport runpy 35 0p data = [18,25 2, 3, 4, 55 6, 7, 8 9)y [28, 43, 12, 13, 14,'15, 26, 17, 38, 19), [20, 23, 22, 23, 24, 25, 26, 27, 28, 29), (0, 32, 32, 33, 38, 35, 36, 37, 38, 39), (40, 42, 42, 43, a8, 45, 96, 47, a8, 48)) saisplay original array are = np.array(aata) print(arr) e123 4567 8 9) [a0 a4 22 33 26 25 38 27 38 13] [20 21 22 25 26 25 26 27 28 29) [30 31 32 33 34 35 36 97 38 39] [40 43 42 43 44 45 46 47 48 491] applying the for Loop to show each elenent in array for elenent Sn row print(elenent) ~ Exercise 10 ‘create a program that tests whether the values of an array are finite o infinite Given array arrta e mparray((2s 8, 2,34 4, meet Note: 1. The sample program checks whether the values present inside the array are finite or not by using the sft) function which wil retum a boolean value 2. The sample program checks whether the values present inside the aray are infinite or not by using the isnfQ) function which will return 3 boolean value Finport nunpy Libraries and nane it to be mp. nport nunpy 35 0p + Q101 Finte value feneate nunpy array area = np.array( Ct, ® 2, 34 4, mpvint) saisplay original array print (arrso) [ae 8 8 ane “chock Finite value finiteva = np-istinite(arrte) print("Fintte values:", finiteva) Finite values: [ True True True True True False) + Q10.2 Infinite value seri = ep.array((, 8 2, 3, 4, np-tee) saispiay original array print (arrs0) ta anf] fcheck infinite value snfinsteva = np.dsinftarrta) print(*Infinite values:", infiniteva) Infinite values: [False False False False False True] > Question 1 \With your high school reunion fast approaching, you decide to get in shape and lose some weight. You record your weight every day for five weeks starting on a Monday. Dally weight lost formolar: Daily weight lost = np arange(5*7)/5. ‘Today, My weights 185 Pounds ease, build an array with your average, min and max weight per weekend (Saturday and Sunday) nport rungy 35 0p | Given ata Gaidy_nesgnt lost ~ npvarange(S*7) / 5 today weight = 285 weights ~ todsy_weight ~ caily_welant_tost print(wedgnts) 185. 186.8 166.6 386.4 304.2 284, 183.8 199.6 109.4 183.2 283. 262.8 392.6 3824 192.2 182. 18 181.6 181.4 181.2 181. 190.8 280.6 200.4 4390.2 190, 179.8 179.6 179.4 17912 179, 178.8 178.6 178.4 278.2] wookdy_weights = weights.reshape(S, 7) f Weight on Saturdays (ingex 5) for each week wolght_on saturdays = weekly_welghts(:, 5] f calculate the average weight on Saturdays verage_welght_on saturdays ~ np.tean(welght_on_saturdsys) print(*wedght on saturdays: print (wesght_on_saturdays) print(*\niverage weight on saturdays:*) print average weight_on saturdays) eight on saturdays: [age 382.6 262.7 379.8 378.4] Average weight on Satundeys: nin_saturday weight = np.atn(vetgnt_on saturdays) f Pint mininun weight on saturdays Prine (#°Miniaun wetght on Saturdays: (min_saturday wetght:.26} 185") rnax_satunday.weight = np.nax(veight_on_saturdays) # Print maximun welght on Saturdays print(#*Haximun weight on Saturdays: (nax_saturday_weight:.24) 18s") Mininue weight on Saturdays: 278.48 Tbs axinue weight on Saturdays: 268.00 Tbs sunday_weights = weekly.wetents(:, 6) average_sunday_veight = np.nean(sincay weights) print(*Height an saturdays Print (sundsy. weighs) print(“\niverage weight on Saturdays:") print (average_suncey.weight) nin_sunday_wesphe = np.nin(sundsy welgnts) print(#*Minimun wetght on Saturdays: (ain_saturday_wetght:.24} 19s") nax_saturday weight = op.nax(sunday_veignts) print(#*Haximun weight on Saturdays: (nax_saturday_wetaht:.24) Tos") eight on saturdays: [isa.a 82.4 181, 479.6 378.2] average weight on Saturdays: Question 2 ‘create the 4x7 array called “ar” that starts with 1 and steps by 2. However, note thatthe first element in ezch row is always 4 more than the last element in the previous row. step Size = 2 are = np.zeros( (nous, cols), otypentn are[®, :] = np.arange(start.value, start value + cols * step size, step_size) for 5 in ronge(, rows) are(i, 0) = arr(t = 2, a) #4 are(s, :] = npcarangetarr(t, @], arr{t, @] + cols + stepsize, step_size) print(arr) [La 3s 7 92033) [a7 29 21 25 28 27 29] [35 35 57 39 42 43 45) [a9 5363 98 57 59 6317 Question 3 Youte a vinditve professor Band one of your pet peeves is when students rush through thelr exams. To teach them a lesson, you decide to ‘give eros tothe fist three students who scoreless than sixty, inthe order they turned in thelr exams. If there are less than three stundents who get sear les than sixty give them zero, Use Random Number Generators to generate the score for 15 people. Let range of the score is 0-100. Identity the fist three values ess than sixty and replace ther with zero. Display the scores after updated Hint: npargwhere and np put fF Generate rangon scores for 15 students in the cange 9-100 np.randon.sees(82) 0 For reproducibility randonscores = np.rangon.randine(®, 101, size-15) peint(“original Seores:*) Print(randonscores) count_replacenerts = scones = [8 if Score « 68 and (count_replacenents ‘= count_replacenents + 1) ce 3 else score for score An randonscores) sndices_less_thon 6 = () for £ in range(ien(scores)) Sf scores[ i] «60: ‘snaices_less_shan_6®.append(4) print(“Indices of scores less than 6@:*, Indlces_tess_than_6@) ‘Scones_less_thon_6® = [score < 68 for score tn randonscores) print("scores leas than 6@:", scores less_tnan_6@) seores_less_than 6 = [score for score In scores IF score < 68] rint(*Scones Less than 6@:", scores_less_than_60) print("\eScores after Replacements") print(scores) esginal Scores: [51°92 26 71 60 20 62 66 74 74 87 99.232 21) Indices of scores Less than 68: [8, 2, 5, 12, 13, 14] Scores less than 66: (True, False, True, False, false, True, False, False, False, False, False, False, True, True, True] Seores less than 68: [0, @, 8, 23, 2, 21) Scores a¢ter Replacerent [, 92, 8, 74, 68, 8, 62, 86, 74, 74, 87, 99, 23, 2, 21] Question 4 Create @ 1x2 aray of foats(maximum 2 decimals) where each row represents a movie. The fist column represents the movies rating and the ‘second column represents the director rating Given array eatings = np. tound(np.randen.rond(2,2)%0, gecinasa2) extingst2,7,91, (6,0,8,61] = ronan (Create a third column that represents the overall rating. The overall rating Is equal to the movie rating if it exists, otherwise the directo’ rating int: np.concatenate, np put np resize nport runpy as 0 ratings = np.round(np.rancon.rand(3®, 2) * 30, decinals-2) ratings[[2 2, 7, 8], [8s 8 8) @]] + mp.nan f calculate overall rating overall = npawtere(np.tsnan(ratings), @, ratings) overatt = mpaahere(overaii{:, @] == ® overall[:, 1], overati{:, @)) f Conbine ratings and overall rating into one array ratings_with overall = np.nstack( (ratings, overallreshape(-t, 1))) ratings with_overail frp. isnan(ratings_with_overail)] = @ print(“orsginal Ratings:") Print(ratines) print(*\nchange te @:") Print(ratings-withoverali(:, :-t]) ginal Ratings [e-ss 7.22] [nan 6.03) [nan [saz [ozs a [5.78 [nan b. [nan change Tre.56 print("\noverall Ratings Array:") print(array) [0.36 0.00 6.47 6.32 0.23 4, 9,74 6.18 3.89 8.6 p-expand_dins(overall, axise1) print (array) {2.56} [e.01] [e371 [s.az} [0.231 ey [3.74] 1 Be} Tee 11 Join = op.nstack((ratings with_overal(:, tt], arrays, -t2))) pranecoiey {10.56 7.22 0.56} fo. 6.81 een} fe. 6:37 ear} {saz 8.87 eia} {elas 5.25 0123} tear e. y {sire 2°33 a7} fo.” 6.38 68} (5:82 5.03 5-02} fe ae ae hy > Question 5 You own @ taco truck that’s open 24/7 and manage five employees who run it. Employees work solo, eight-hour shifts. You decide the best way to set their schedule forthe upcoming week Isto create a bunch of random schedules and select one that looks best, You builé @ 100321 array of random employee ids where element (i) gives the employee id working shit} for schedule Given data gxreraton = nporandondefault_rne) Senedles = genertor.integers(low, Nigws, sizer(16, 211) # (30... 2007 pes 33a) # (ve2..a2a) fe ezr3aa) #263 ..232) eae 2aanT [A Schedules valid as long as no employee works two consecutive shifts. Get the row indices of all valid schedules. Note: np.setprintoptions(threshold-sys maxsize) use to show the maximum array 9.50 pontoptions(tnesholéesys.nxsize) int: np.rendom choice soport sy nport runpy 35 0 np. set_printoptions(thresholdesys.saxsize) # oaven oota fenerator = np.randon.default_eng(s9) Schedules = gorerator-integers(los-8, highs, slzes(1@e, 21)) print(schedues) [n222a2a2234s002223344) 5) penerator.Antegers(low=2, nah Sf scheceles[i, 4) seheaules(t, J] white j < 28 print Schedules) jet np.set_printoptions(threstoldarp. inf) # Show entire array f Display the rearranged schedules for £ an range(s99) [ro20soi0323a343a21831) “ [2022340e23e2032324341) [2134031e0832a30120212) [ei2eiesie43e230102423)) for £ an range(s09) for 3 in range(3, 22) while schecules{i, J) == schedules(t, 3 - 1): schegules[i, J) = generator.integers(Low-e, nines) f Format each row as an array and join then in one Line formatted ross = [Farray((ste(ros)})” for raw in schedules) output = > "-Join(Fornatted, rows) 1 Pint the formatted output print (output) array((s 23.20240431231421203 2) array((424324232423431303021)) array([1 3023402134 oo » Y 05 completed at 730° ex

You might also like