Transcripts
1. Introduction:
2. The IPython Console: the I Python Conso is used to run code interactive. Lee is an enhanced command line are a pl environment for Python. Some of its features include command history, browsing, available even between sessions, input and output. Cashing out a Completion and MAWR I. Pilon is used as a colonel or back end in this Spider i D. And in Jupiter Notebook, which will be discussed in the following lectures. Let's open the iPod income so right away and check it out. If you install the anaconda environment, you can open the anaconda prompt from the start menu. If you are on windows So let's do it. Starred Anaconda Anaconda Prompt Then in the anaconda prompt Just type I Lytham. This will open the eyes. Python come soul. You can see the version of bison and the version of I Python you're using below. You can see the input prompt In one. You can touch any python code here. Let's try something simple, like to to the power of five and you get out. One. This is the output from this code, as you can see, echoing works just like in any other Are PPL the corresponding output you get is denoted as out one. You can also see the next input prompt the numbers in the square brackets in the inputs and outputs are incremental automatically. We call these inputs and outputs cells. I pathan also creates variables that's told the inputs and the outputs Inputs are stored in the end list. Outputs are stored in the out dictionary. They can be accessed by induces and case respectively. Have a look to plus five. This is our input. And this hour output seven. Now we can use the in list with index one. So this is what we get. This is what was stored in the enlist under one. How about output out with key one 32. This is what was stored in the out dictionary under the key one. We can also praying the whole enlist. This is what we have under zero. We have an empty string and then this is under one here to here. Then we have in within eggs. One. We're just under three out with key Juan, which is under four. And here we have the latest in we can also print out. As you can see, there's a dictionary 12345 These are the keys, and the values are 32 here, seven here to the power of five, which is here and so on. Now the two recent outputs are cached. You can use a single under school for the most recent output and a double underscore or the one before. Let's have a look. Three time's sakes. 18 Tim, Divided by three three is the so called floor division. So we get indigenous as results and now we can use underscores leads. Use double underscore divided by single underscore and you get six. You have to division, so the result is afloat. Number. So what do these underscores mean? The double underscore means 18. The single underscore means three So a team divided by three. So this is the recent output and this is the output before the recent one. When input cell is executed, the output, if there is any, is by Defour displayed in the corresponding upper cell. If you don't want this behavior, just put a semicolon at the end of the statement. So let's have a league two plus four. So by default, we get this out of here. How about this two plus for Sami. Colin. Now we don't get the outward. You can also use the semicolon. Two separate multiple statements have lick a equals five sabako A. So you want to echo the variable? And what you get is five. I pythons supports auto completion. If you press the tab, key out of completion is activated. Let's import Nam pie. So import? No. Why? As and P and then type and P DOD s I. And then let's press tab. This will display all names in numb by that's done with as I sign sin etcetera. You want to read the documentation string of an object? Just type a question mark. So, for example, and p God question more. And here we get the doc string. Then we can press cute to quit.
3. Magic Functions: in I Python, we can use extension commands known as magic functions. One line commands are preceded by a single percent sign, and commands working in a wholesale are preceded by a double percent sign. Let's activate I pi than first. You can use the percent L as a magic command toe laced. All available magic functions so percent L as magic. So if a little line magics and available cell magics now, if automatic is on the percent, perfect is not needed for lying magics. If you're interested in what they do, you can check them out by following them with a question mark. So, for example, we have a magic function like this percent Matt plot lib, and I want to check out what it does. So question Mark and we get the doc String set up. Met Played lib to work Interactive Lee. This function, as you activate, met good lib, interactive support and so on. It's quit now. That's not a dig at two of the most frequently used magic functions time it and time, and also the counterparts used for the whole cell with double percent signs. Now the time it command runs a Pilon statement multiple times and estimates its run time. It doesn't return the result of the expression. If we need the result, we can use the time and time commands, but the owner around this statement once so they're not very accurate. Let's first define a function and then use the two methods to see how much time in needs to execute lets you find the function than death. Kid. We one parameter an return. You have a list comprehension I to the power of three for I and arrange and okay. With this function defined, let's use the time of the magic function to see how much time it takes to execute this function. So here's our magic function. Time it. And here's our function Cube and let's pass the argument off. 10,000 now 9.7 minutes. Seconds plus minus two. Have a 90 microseconds pollute, so there's the result. And now let's use the time with it. Cubes equals Time Cube 10,000. Now what time? 4.96 milliseconds. Well, medic functions are also used in Jupiter Notebook. We'll have a look at some of them when we need them.
4. The Spyder IDE: the Spider integrated development environment is used to write python modules and packages as well as run python code interactive. Lee, through its integration with the iPad and console spider, is especially suitable for working with scientific libraries. Let's open the I D and have a negative. So we have a here under Anaconda Spider. The idea taken states of several pains. So here you have the source code editor, the I Python console, the Variable Explorer, Find Explorer, Help Pastry log and some War. The source Code editor has all the functionality. A good code editor should have code highlighting auto completion for emphasis, matching indentation, guidance and so on. It allows you to work on multiple file simultaneously. Now let's enter some simple python code print. Hello, print world. Drown this coat in the council. Just press F five here you can see the output. Hello world. Now I'm not going to use this idea in this course, but if you want to use the spider idea on a regular basis, the idea he has a very good detail tutorial then you can use to begin with. In this course, however, we're going to use Jupiter notebook. You are going to discuss in a moment
5. Introduction to Jupyter Notebook: The Jupiter notebook is a Web application in which Python code can be written and executed through a Web browser. It is used around your code. Collect the output produced by her code and in bad text, graphics, videos, figures and equations, all in one document. In Jupiter, we have a front end in a bag, and the front end is the user interface. So actually, the notebook. It takes care of entering and organizing code and other stuff, and of presenting the results of computations to the user. The back and is known as the Colonel. It performs the competitions and maintains the state of the interpreter. There may be multiple kernels, for example, for different programming languages or different versions of Pathan in order to launch Juvenile Notebook. Just talk, Jupiter Notebook and ER, and here it opens. This Tarts notebook Colonel and the Web application on local host poured 8888 by the Ford on your dashboard page. We can see all the notebooks toward in the directory from her Jupiter note who was launched . You had old notebooks. The notebooks are stored in Jason format with the I P. Y. And be extension. You can now open any of them or start a new one. Let's create a new notebook. Take the new button. Faison Fly. Now you can change the title to something meaningful by clicking on the title field here. And let's say our first no dick is the title. Now we are ready to enter some text. Big Python could or plain text. The notebook consists of input and output cells. There are several types of cells you can send the type of a cell in the Salman you so type . It can be code markdown and so on. We're going toured with Code South's most of the Time you Can and Jawan or several lines of Python code in a code and Bruce L. And then press shift plus enter to execute it. The code is sent to the colonel process, where was evaluated by the Python interpreter. And if there is any output, it's sent back to the output cell. Let's try it out. Let's type something like this a equals five. The equals a is a string. Now print a Times B. Now, in order to execute, it must render shift enter and here we have the output this string is repeated five times, So this is a code cell. Now let's have a look at a markdown sell. Let's change the time of this cell to mark down. Okay, now a new markdown cell. We can just talk Plain text and Morgan Cell contains text interpreted using the more down language. This text, maybe italicized board over met it in a different way. The market rules of the markdown language are, however, beyond the scope of these courts. The South could be one of two modes. Edit mode and command mode. Edit mode. Let's you added the contents of the cell in orderto under any mode. Just click the cell press and ER. Now this cell is now in command mode. If it Clignet, it changes the color to green, which means it's an edit mode now, and we can added the content of this cell. You can leave at in mode by pressing escape, so if it press escape, I'm in command mode again so you can tell whether you are a ned emote or command mode. By the color of the cell, Green means edit mode. Blue means command mode. You can manipulate the cells using the many or keyboard shortcuts. In particular, you can insert cells below or above the currently selected cell. You can deliver cell copying pace, it converted to different type and so on. You can move between cells in command mode, using the up and down arrows. So up, down, up, down. And here's some his was short cuts for the most common operations. Try them out. Be bees used to insert and you sell below. So let's like this cell and that's type be. And here in new cell is inserted. Now A is used to insert a new cell above. So if I'm how, press a I'm inserting and you sell about this one. De de he's used to delay this cell. So with this self selected less click D D twice now this cell is now dilated. Acts is used to cut the cell, so this cell selected let's press acts see, is used to cover the cell. So we have this cell here. That's press See, now it's copied. Now we can pace the south using V now, just a reminder. All these shortcuts only work in command mode. So when the Sally's Blue let me have M m is used to convert to mark down. So let's select this code cell and press am. Nothing is marked down. Why is used to convert to code? So the opposite. So now this is a markdown sell. Let's press why and now it's a code self again. Now is it mentioned before up there? Oh, and Down Era are used to select the sales. Down up. The enter is used to enter any mode. So if I select this cell, which is now in command mode, blue and press enter, I know entering any mood and escape is used to exit that mode as mentioned before. Shift plus enter is used to execute the cell. So one more time with its self selected last press shift and er and here's our upward now s is used to save the notebook. And finally, if you get lost, you can always hit age. Age is used to display ahead window with a laser, all available keyboard shortcuts. Were you down with a car in session in your notebook? Save it and close it so it has to save, and to close it, you can go to the file menu close and halt. Fine. Finally, you can quit the application altogether by pressing. Quit. We have shutdown Jupiter. You can now close this tab to use Jupiter again. We will need to relaunch it. Servers, tops, Okay.
6. The numpy Module: If you want to use Parton in science, there is one module all other scientific modules made use of numb by number. I leads as work on the race, which in turn leads us. Were paid computations for a set of values in one go without using the slow for lives. But work on H element one by one. Essentially, we can organise colors and raise scullers are just numbers. A race may have one dimension. We often call them vectors. Then two dimensions only often refer to them as mattresses or any other number of dimensions. Before going any further in theory, which is jump into some code, the first thing we have to do is import the non pie module we almost always imported, using the alias and P so import number by S and P. Then you could create a simple numb by array, a equals and P array. 12345 We were talking about all the different ways of creating them by array. Soon, for now, let's just use the ray function and pass a list of integers to. And now let's print it out brained a. And then let's make a simple computation five times a. Now let's hit shift plus enter and here's the out Good 12345 These are numb by array. We should create. We're here, and this is the result of this computation. If we multiply the array by five, the operation will be performed on all elements. This way of performing operations is called victory Ization. It's very efficient. We don't need any four lives to perform the operation sequentially on each element. Using numb pie in scientific programming is generally much faster and more efficient than using pure bison. Victory ization is one of the reasons Here's some basic features of number. I raise the core of numb buys implemented in C, which works much faster than Pathan number. I raise our homogeneous and typed, which means all elements in an array are the same type, like all ends or all floats. For example, number a raise have a fixed size so they can't be resized ones created without creating a new array. The number I module also provides lots of operators and functions to work with the race. We'll have a look at just a tiny selection of them in the course
7. The Attributes of a numpy Array: In the previous lecture, we created our first number array. Let's wait another array to have something to work on. So first we have to import numb pie. Let's create an array Acts equals and P array to 46 eight 10 for example. That's pretty. Now she's ender. Here's our array. The class the num pie uses for the erase is the Andy Array class. An ND array object contains the data stored in the array, but also some other attributes that correct Rise the array. We're making use of these attributes throughout the course, so let's have a look at them now. If you want to see all the attributes that are available, just use the question. More imitation used in Juvenile Notebook to get help so NP and D array question more. She ender. You have the docks train. Let's look for the attributes. He would have attributes well for our needs. We have a look at the following attributes shape sighs and dim and bides and de type fine. Let's start with a shape. Attribute the shape attributes is it tipple that contains the number of elements in age dimension. So let's see how it works with our ex array ex dot shape shift Enter five comer. So these a triple article contains just one number because our array is one dimensional. Now let's created two dimensional array by passing a waste of laced as the arguments. So why equals and Pierre Ray now a list of lists. So the other lists and I have three layers inside. These last the 1st 1 A's want to. Then we have 57 and then we have 46 okay, and now we can echo the array she had under. Here's Our Array. It's to financial. Let's check it out. Why shape shit andr 32 this hour to pull. So we have three rows is the first dimension and two columns. There's the second dimension. Well, okay. The next attributes is ending, it tells is the number of dimensions, so it will use it on our X and Y rays. We should get one and two, respectively. Let's check it out. So print X and him and friend, why and in keep enter one this one dimension in acts to two dimensions in why now the next attributed size. It tells us the total number of all the elements in the array. So there are five elements in acts and six elements in Why let's check it out. Shift Enter. Yeah, five and six, respectively. The next attributes is D type. As you know, all the elements in an array, all the same type. This attribute is used to check what that time the elements in the array are. In our case, both acts and why contain integers. So let's check it out, friend Axe de type print. Why de type should enter. Indeed, you're in danger. We're talking about deputize. Used a numb pie in the next lecture we have here is a 32 bit integer. So an integer that takes up 32 Bates or four bites because one bite equals eight bets. Knowing the dinner type of our elements and their total number, we can calculate the total size of an array in acts. We have five elements, four bytes each, so five times four equals 2020 bytes altogether and why we have six elements four bites age so six times four equals 24 bites altogether. We don't have to make these advance calculations. Instead, we can use the end bites attribute that you tell us how big our arrays are. So print acts and bots print why and bites Chip Enter, Yeah, 20 bugs and 24 bites, respectively.
8. Data Types: in the previous lecture. We're using the D type attribute off the ND array class to check the data. Type off the elements in the array. We know that all elements of a number array are of the same type. Unlike in a regular pilot, unlaced or the elements may I don't have to be of the same type. Let's create an array and use the attribute again to check the data type. So first we have to important EMP. I Now let's create an array, A equals and P array four 27 And now let's check the D type of these array So friends a de type hit. Enter integer 32 bed. So for bite integer, let's try this array be equals and P array 0.2 0.4 2.1. As you can see, these are floats. Print be de type chipped ender float 64. So now they are 64 bit floating point numbers. Okay, here's another one. C equals and P array. Three 2.4 two point aid plus 1.2 j print See de type camp lacks. Want to aid, As you can see if we try to put an integer and float and a complex number in an umpire. A. There would be all up cast a complex number because both integers and floats can be easily converted to complex numbers. The maybe miracle data types that we can use and number are signed and unsigned. Int urges like a big integers. Extend bait, integer 32 bit integer, 64 Bed in Danger and also 8 16 32 64 unsigned Integers, then float like floats. 16. So 16 bed float number load 32 followed 64 then complex numbers like Complex 64 Complex 128 Complex 256 and bulls. The numbers tell us how many debates are needed to represent a number of these type. So, for example, Complex 64 means that we need 64 bits or eight BIS to represent this number. Apart from this, we can use no numerical types as well, like strings objects of user defined types. From now, however, we concentrate on the numerical types. So what do we want to create? An array of eight bit unsigned integers these air No negative integers that can be represented on a bets Let's try d Equals and P Array. 123 Friends de de type shaved under integer 32. Well, the elements 12 and three can be definitely interpreted as unsigned a bait integers because they are no negative and eight base is more than enough to represent them. However, as we can see, they're treated as 32 bit signed integers. If we really want them to be of a specific data type, we can make them be of this type, bypassing the D type argument to the rate constructor. So in our case ruled Half E. A equals and P array, while 23 de type equals and P You I anti aid, which stands for inside a bit. Integer now that's print de type shift enter, and now they have with you on unsigned a bit integer now. Another example. Let's create an array off 64 bit floats s equals and P array 123 de type equals and P float 64 print half de type. She and ER float 64. Now, as far as the D type is concerned, and P float 64 there's also another Syntex for this. Have a look. We could have written these like so f equals and P array. 123 de type equals if aid as a strain friend f de type, she has ender and have the same results. So here the string at eight means an eight byte float, Would you say, as a 64 bit float? We can also only generally specify that you want an integer afloat or any other time. For example, G equals and P array 123 and so generally end friend G D type shit ender when you get a 32 bit integer or like this age equals NPR. Ray. 123 complex. A friend age D type she's under and haven't Contacts Number A 128 bait contacts number We can also treat the data is bully and values where zero is interpreted as false and any other number is true. Have legacies. I equals and P array five zero negative, too. Zero seven de type equals bull. First, let's bring the array friend I And then let's print the d type of this array. Chief Tender. So here we have the array True force True Force to As you can see, force corresponds to zero and true to any other number. And the time is bull. After he created Ray, we actually can't change the type of the elements. What we can do is typecast the array by creating a new array. We can do it like so. So first, let's create our next array. J equals NP array 123 float Print J and print J de Type. So these air flowed numbers and how it's type Kasey Ray by creating a new way to complex numbers. So J equals and P array. Now we can use our J array, but change the d type Teoh camp lacks. Now let's print J again and thats print j de type shave and er so you have our first array of flows 123 s floats and this is the type the 64 bait float. And then after we typecast the array to companies numbers, we haven't array of complex numbers. I hear. And here you can see the type. Alternatively, we could use the S type method off the nd array class. So here we have our J A radius flows, and then we can use the S type method like so Jay equals J as type count Blacks print J print J D type shift enter, then you have the same result.
9. Creating numpy Arrays with Constant Values: we've been creating them by a race using the NP array function and passing a list of elements to it as an argument. Here are some examples again for us, that's important, imply. Now let's create an empire. A. The way we've been doing this so far, so a equals NPR A. And he has a list of elements. 123 Print a chief ender and his are array or it two dimensional array like this. Naturally, we can first define the laced and then pass it to the MP array. Function. Public B equals it's a nested Last year, 3.6. So we have floats 2.9 and another NASA laced 0.9 7.2. Okay, now B equals and P array of the print Be chief ender. And here's our two dimensional array created days way we can use the array function. Also, it triples have Leg C equals Now a couple four six nine C equals and P array of C. Brinn See Chief Ender. And here we have our one dimensional array. But sometimes we need a race containing specific data like constant values, increasing or decreasing values. Uniforms, paste numbers, random numbers and so on to this, and we can use quite a lot of functions. Besides the basic NP array function we've been using so far, that's how I look at something that was frequently used once. If we need an array where all the elements have constant values, we can use one of the following functions and p zeros if all the elements should be zeros and P wants if we need an array of ones, np fool if we need a constant value different than 01 The film method If you want to fill an array that already exists with some constant values, and here's how we can use these functions first and P Zeros. Let's create a three dimensional array with dimensions three by five by two filled with zeros, so de equals and P zeros and we can pass a to pool with the D mansions. Three five to now, Print de Chief and er. What we get is a three dimensional array of zeros with dimensions. 3123 512345 and 212 And now let's create a one dimensional array off 25 ones. So e equals and P. Waas 25 print e shift enter, and he would have it. Now let's create it to Dimension Array with Dimension seven by three, where each element is set to 5.7 to this and will use the full function f equals and P fool . Now the dimensions seven by three and the constant value 5.7 print atthe achieved under. And here it is as seven by three dimensional array filled with this number. We can also create an empty array, using the MP empty function and then filleted with constant values. The empty function creates an array with un initialized elements. Let's create one check the dead I've contains and then filled with elements, said to five. By the way, the day got any empty array, maybe different, then presented here. It's accidental, so let's create an empty ray. G equals and P empty, and the shape should be a four by five that's putting out. Then let's use the fill function to fail the array with fives, and that's pretty again she has entered. So here's the data. We got the first time when the array was un initialized and here after we set the value to five, we get an array of five. There are also functions that can create a race filled with zeros, ones, other constant values or un initialized values based on other arrays so they can take the shape and then a type after other rays are. The elements they contain are different. The functions are called and P zero is like and P ones like and the fool like an empty empty like That's how you get them in action. First, let's create a two dimensional array of ends and a one dimensional array of floats, h equals and P array 43 to a. So this is our two dimensional array off ends, and now I equals and P Array 0.9 1.2, 3.2, 2.2 four, 5.2, 5.4 0.7. So this is our one dimensional array. Off floats. Now let's print them out. Print age print boy. Okay, she has ender. Here they are are two dimensional array of ends in our one dimensional array of floats. Now let's create some arrays that have the same shapes and Deva types as the T raise above . First, let's create to rates that should be filled with zeros. We can do it immediately. Like so. Print and P zero is like age and and P zeros like I shift Enter. As you can see, what we get is a two dimensional array of ends filled with zeros, integer zeros and a one dimensional array of floats, third with flowed zeros. Next, let's create to raise that should be filled with ones. So print and P once like H print and P, once like I achieved ender and we got the same. A two dimensional array of interview wise and one dimensional array of float ones finally to raise that should be filled with three So print and P full like AIDS and the constant number three print and P full like I three shave under. And now we get a two dimensional array of integer threes and one dimensional array off float freeze
10. Creating numpy Arrays with Spaced Values: If we want to create an array with incremental or detrimental values, we can use the NP arrange function, which works very much like the budding range function in Brighton. Or we can use the n pill in space function. But first, let's important empire and now we're ready to go. The MP arrange function takes up to three arguments just like the range function startle you and value not included and optionally this step. Here it is with just one argument and P arrange Tim Shift and ER, and what we get is array of numbers from 0 to 9. So, as you can see, this is the end value, which is not included. How about two arguments and P. Arrange five. Tam Shift and ER now haven't array off interview numbers from 5 to 9 because 10 is not included again. Finally, let's also use a step so NP arrange from 100 down 20 with a step of negative five shaved ender. And here's our array. Now. The lens pace function also takes three arguments, but hear the end value is included. Besides, the third argument determines the total number of elements in the array, so we have our in space function and P. Lynn Space Start Value five and value 10. These values is include, and now how many elements do we need? Let's say Aid Shift and er What we get now is an array of fluid numbers between five and 10 and there were eight elements. Uniforms paste altogether. If we don't want the end value to be included, Weaken said. The endpoint cured argument to false so and pay Lynn Space Start Value five and value tan Aid almonds. But then we can set and point to false, which means the end value 10 would not be. Include Shaved Ender. As you can see now, 10 is not included in the array. We can also create a race with Roderick make sequences. The function we need for that is an pielach space. It works just like and pill in space, which means it takes three arguments from two and how many elements But the values are distributed. Logarithmic Lee by D. Ford. It uses the base 10 logarithms, but you can change it by setting the basic your argument. Some examples. How about 10 elements? Logarithmic, please paste in base 10 between one and 1000 well and P locks base and now wa ace 10 to the power of zero to the first argument, a zero 1000 stand of the power of three. So the second argument the N value is three, and we need 10 elements. Shave and ER. And now, as you can see, these values are logarithmic Lee spaced. We can also change the endpoint argument to false and change the base. Let's say to to have a look and P locks base zero three 10 and point equals Falls Bay's equals two. Now what does it mean? And point equals force means that the last value would not be included. Basic was too, is the base off the log rhythm and now the start value is zero. So two to the power of zero, which is one and three is the end value. So two to the power three, which is eight. So now we're going to get 10 values between one and eight aid not being included. So shaved and er and this is what you get. 10 evenly spaced logarithmic lee spaced values between one and 88 not being included.
11. Creating numpy Arrays with Set Diagonals: in the previous lecture. We learn to create number erase filled with constant values, incriminating or dick amending values as well as uniformly or local rhythmically spaced values. But there are even more ways of creating a race. Let's have a look at some of them. Here's some functions that come in handy when creating two dimensional race or matrices. The 1st 1 is NP identity. We use it to create a square matrix with once on the diagonal and zeros as we're, we have to pass the number of elements in one dimension as an argument. First, let's important empire as usual. And now let's create a three by three identity matrix and pay identity. Three. Shaved Andrew and he would ACE wants on the diagonal zeros as where, and here's a five by 51 to enter. Okay, there's a similar function and p i. It also creates an array with once on the diagonal and zeros elsewhere. But we can also pass an offset as an argument to shift their diagonal up or down. Let's start with no offset, so we weren't just like identity and P by anyone. A five by five matrix shaved ender so The result is identical as here. But now let's have the offset to one so the ones will move up and p i five. And now the offset K equals one achieved under. As you can see now, the ones are not on the diagonal there shifted up. How about an asset of negative too? So the ones should go down twice. Have a week and b I five k equals negative, too. Shaved ender. As you can see, here's our day agonal and there was are down it really different values and the diagonal, not Juan. We can use the m p D I G function. You see this functionally used a one dimensional array to provide the elements for the diagonal. We can also said the asset. Here's some examples. So let's say we want all elements on the diagonal to be said to four and they should be five elements in each dimension. So and P. D I, A. G and P array 44444 Shaved under. Now we have the force on the day agonal. We can achieve the same like this and pay D I a G and P fool. 54 achieved Ender. What now? Let's create a matrix with the elements on the diagonal from 1 to 10. We can do it like so and P. D. I. G and Pierre range 1 11 So this would produce the numbers for the diagonal she's under now , As you can see, we have 12345 etcetera on the diagonal and now the same with an offset. So N P. D I, A. G and P arrange 1 11 k equals, let's say negative four shaved under. Now, As you can see, these numbers are not on the diagonal. They are shifted down.
12. Creating numpy Arrays from Functions: there is another useful way of creating on by race. We can create a race from functions to this ant. We use the MP from function, function this function, creating rate by executing a function over Ridge coordinate. So the number of parameters the function takes must be equal to the number of dimensions. Let's start with something simple. A one dimension array by. The first thing to do is to import number. Of course. Now let's create a function that takes one parameter because it's going to be used for a one dimensional array. So Death f with axe return acts for a simple Now let's create an array from this function. The MP from function function takes the function as the argument, then the shape of the array as the second argument and optionally we can also pass. The D type is the third argument have a lick, a equals and P from function half. So the first argument is our function. Seven. So the second argument is the shape of the array and de type equals end. This is the D type Now let's print a shift. Enter and here's our array. 0123456 So you have a one dimensional array with seven elements which are integers. This isn't because we passed the shape to pull seven to the function. The values Arctic consecutive values returned by the function. So Dave, the function takes zero return zero. It takes one. It returns one and so on. Now let's modify our function a bit to see the difference. Well, Death F of acts return five times X plus 0.5 now B equals and P from function. Now our F function and the shape, Let's say seven again. I want to mention array Be shaved under. And now we get this. Now the function returns five times zero plus 0.5. So is Europe in five five times one plus 0.5 so 5.5 etcetera. We often use Lambda functions instead of functions defined using the death cured. Here's how we could rewrite our last example. C equals and P from function. Lambda Axe five times X glass 0.5 and the shape see shaved under and we get the same results. Or if he preferred to keep our code clear and readable, we could date like so F equals Ramda Axe five times X plus 0.5 D equals and pay from function F on the shape de shift Enter. Gonna have these again. Okay, now let's have a look at the multidimensional arrays. Let's create a two dimensional three by four array. Here's the functionally use. Now we need to parameters because their two dimensions f equals Lambda X y to times X plus . Why? So these are a function, and I'm ready to create the array. MM equals and pay from function. Yes, the shape three by four and let's set the D type to and e shift enter. So when we get AIDS in the first road to time, zero plus zero is zero, then to time zero plus Juan is one two times zero plus two is two two time zero plus three is three, so the value of acts is zero. For the first row, the value of acts will increase along the axis. So in the consecutive rose, where is the value of why increases along the second axis or D mansion? So along the columns now in the second row X would be equal to one. So 1/2 2 times one plus zero is too. Two times one plus one is three, two times one plus two is four etcetera. In the third row, access is equal to two, so have two times two plus zero is 42 times two plus one is five, etcetera.
13. Indexing and Slicing numpy Arrays – the Basics: Now let's talk about indexing and slicing. NPR raise indexing and slicing one dimension a race is pretty straightforward. It works just like with python laced. Here's some examples. First, let's important Empire Force. Now let's create an array, Hey Equals and Pierre Ray from this list, too. 46 three five seven, for example, Let's print out who it is. Now let's get the first element. So there's how indexing works in that zero. You get the first element. Nothing special about it. Let's get the last element A with index negative one. See if Ender and here we get the last element. And now let's slice from Index to to index five, which is exclusive. So a to 25 Nothing Special Shift and ER, and this is this life we have. The elements between Index two and five five is not included, and now let's slice from the beginning to index five. So a from the beginning. 25 Here's ours life and now that slice for the next three to the end. A three to the end. Also nothing special. Now let's get all the elements shift ender. Here they are, and now let's slice from Index one to index five. Exclusive with step two. So every other element A from index one to index. Five with step to shoot ender And now when we get is this and now let's have a look at the multidimensional arrays. First, let's create one from a function F equals Lambda. That's why X plus 10 plus 10 times why, for example, they equals and P from function F. The shape should be six by five on the D type should be integer be achieved under his are array. Now, the first way of indexing such arrays is just like python nested lists. So using two indices in square brackets like so, be the first index to the second index four. So here we are selecting the element in the third row, so index to and that faith call him So. Index 4/3 row Fifth column is 52. Shift enter. And so we got 52 while this works. But this is inefficient because it creates a temporary intimated array. Be within exit to in this case, which is then indexed with the second index and more efficient way is to put all the Indus is in one pair of square brackets. So the optimal way of indexing, multi dimensional race is like so day one pair of square brackets and both in this is inside to four. Shift under 52. Well, when slicing multi dimension a race, we also separate the Rangers for each dimension by comers. Inside one pair of square brackets. Here's our be array again. So let's have a look at this again RB array so that you can see all of it. And now let's slice it in a couple of different ways. So first, let's select the rose from 1 to 3 and the columns from two to the end be one pair of square brackets, 1 to 4. Business for the rose from 1234 is not included, Comma. And now, two to the end. This is for the columns. So rose 123 columns to to the end. And this is what we get shaved under. So how can we visualize this? Well, rose 123 123 By columns to to the end. Just call him too. So two to the end in these three rows. And this is what you get here. So as you can see, their first range is for the first dimension or the rose. The second ranges for the second dimension or the colors. Some more examples. Let's select the rose from the beginning to to and the columns from 1 to 2. The indexed three because it's not include and the columns 12 to 23 because it's not included Shaved and ER and this is what we get. And now we want all the rows and all the columns. It's quite simple. Be all Rose comma All Comes, should enter. And this is what we get, just like our original array. If we skip the indices for some dimensions, we're automatically said to Colin. So the whole dimension. Let's select the rose from 1 to 2 and all the Collins be what? Calling three. So the rose from 1 to 2 shift under. We can also use the step to skip some rows or columns. Now we want every other row on the columns from the beginning to to have a leak. Be Colin, Colin and this Step two. So all the rose with Step two, which means every other row and all the colors to two. So we need the next three shift and ER and this is what we get. And now every other row and every other column be every other room and every other column. Shift, enter, and this is what we get.
14. Views and Copies: now the Bruins lecture. We're talking about indexing and slicing when slicing, not by race. We created views on the original race, so we are working on the same original data, which means that if we change some data in the view, it will also be changed in the original array. Have a league first, Let's import number. Of course, you know that's great. An array, A equals and P from function. Lambda X Y 10 times Open grand the sihf X plus one close parentheses. Times open parentheses. Why plus one close parentheses. The Shape four by four and D type end Fine. Let's print out. Here's our array now let's slides Theory. B equals a no every other row and every other column. So here's our be array. Flying now be is a view. Let's change. The first element in B be with index 00 is the first element now should a cruel zero. So as you can see, it now equals 10. But now it should equal zero fine and thats print be enter. So as you can see, the first on B has changed zero. But these a view on the original ray. So this change also took place in the original Ray. Let's print a. As you can see now, we have zero as the first element. He was 10. Now it's zero. And now let's create another slice. See equals a all the rest and all columns up to three. So actually up to two, because three is not included. See shift enter. Here's our array. It's also a view now that said, all the elements in the Seaview to one see we'll raise all cousins equals one. See fine. And now it turns out that these elements we're also changed in the original rain have leg A . As you can see, these Alamance have been changed to ones. If you want to create an independent carpet instead of a view, you should use the capping method. So first, let's recreate our A array. Let's print out. And now let's create a slice as a copy. The equals a rose up to two. So in those three columns, up to two so again index three and then the county method. Now this is our be array, which is now that of you is a copy. And now let's change or the elements. Let's have them to one. For example. So be all rose. All kinds equals one. This is our beer right now or once. But now or original array remains untouched. A. As you can see, this change did not happen here. Alternatively, you can use the anti copy function. So, for example, C equals and pig copy a rose up to 33 not included. Collins the same. These are C fine. What's change? The elements to five see is R C array now, but put it is a copy, so a remains untouched.
15. Fancy Indexing: Now we already know how to index number I raise, but there are other ways of indexing them. Mumbai race, maybe index by other Numb by race or Parton list. We call this fancy indexing. The sequence that is past as an index in square brackets contains the indices, which should be selected. Have a look first, let's import number. Of course. Now let's create the array. We'll be working on a equals and P. Lynn space, so we want 11 elements between two and three. So, too three 11. Here's our A array fine. And now let's select the elements at Indus is 34 and eight using another number array. So a square brackets for indexing and as the index, let's use another number IRA NP array. And here we have three, four, eight. So these are the end. This is I want to be selected, and this is what we get. 2.3, which is at index three, 2.4, which is at index four and 2.8. We just at index aid. Naturally, we can also define the array beforehand. Have a look is our array and P array 34 aid and then we have a indexed with these array shaved and er, and this is what we get the same result. And now let's try it. Python List Here's our laced 348 Now let's index our number array with this list, and again it works now an example with a multi dimensional array. Let's first create one from a function. Let's define the function first half equals Lambda X. Why X plus one in parentheses to the power of Why bless one now be equals and P from function F. The shape should be five by five, and the D type we want is integer. So here's our be array. Fine. Now let's create another array that will be used to index to be arraigned, bar equals and P Array 24 Here's our array, OK, and now let's index to be array with the are array. We want to select the rose two and four as specified in the r. A. So what we need to do is the are we're skipping the columns so its understood as all the columns, but the real should be index with days array. Fine, Chief Ender and this is what we get there Rose two and a four. So, to and for fine. And now let's select the columns two and four be all the Rose columns two and four. So we need these array as the Indust achieved under. And now we have the columns two and four. So to and four Finally, that's like the elements at indices to to and who for so be are are you? The Hour 27 which is road to calm to and 3125 which is Row four column for.
16. Boolean Indexing: Now we know quite a lot about indexing. Numb by race. We also know how to use fancy indexing. But it turns out we can also use Boolean expressions to index, not by race. Then all elements are selected for which the value of the Boolean expression evaluates to true. Well, let's start with importing numb pie. And now let's create an array A equals NP array. Gonna pass a laced So four 12 seven 11 9 22 six 42 61 for example. And now let's select only the elements, which are less than 10 first. Let's see for which element that is true. A is less than 10 shaved under, and now we can see that this is true for the first element. It's for this last in 10. Definitely, it's force for the second element, which is not last than 10. It's true for the third Almond, it's seven lasting 10 and so on. And now let's use this expression this Boolean expression as an index A. With the index A is less than 10 fine shift ender, and we only get those Alan's for which this expression of Allah is true. So 47 nine and six. Now how about elements that are divisible by 11? Well, another 1,000,000,000 expression as the index, so a marginalise 11 equals zero. These numbers are divisible by 11 and the result is 11 and 22. And now let's create a multi dimensional array. B equals and P from function. Lambda Eggs. Why Open Parentheses three minus acts, close parentheses, times open, parentheses. Why, plus three close parentheses Now the shape, Let's say six by six and the D type and fine. Here's our array, Okay? And now let's filter out all the negative and zero values so we can use the following. Index B is greater than zero. This is the Boolean expression, which evaluates a two for no negative numbers online, so he's the results. As you can see, we get a one dimensional array with all the elements for which the Boolean expression was true. One thing to remember about fancy indexing and Boolean indexing is that the new raise our independent erased, not views
17. Reshaping numpy Arrays: Sometimes you may want to reshape or resize your array. Like, for example, Megan Matrix array out of several vectors or the other way around. Turn a vector to Matrix number offers quite a bunch of functions that you like to do just that. Usually there are also corresponding methods in the and, er a class. So suppose we have a one dimensional array they want to reshape into matrix. Here's how we can do it first. That's important by and now let's define our array like so a equals and the array. Very simple. One, 2345678 Okay, now let's use the NP reshape function to make a fool by two matrix out of it. So n P reshape. We used the A array on the new shape. Should bay four by two Fine shift under at this hour array reshaped. Now it's to demand Jewel. Alternatively, we could use the reshape method, like so a reshape and the dimensions four by two and together, saying when reshaping a race like that, we have to make sure that the number of elements will match the new shape. Otherwise, we'll get an error by here Let's try to reshape the Aarej. Two Matrix. The dimensions three by three So nine elements. You have only eight elements. This is impossible. So if you try to do that, which is getting value error Canon reshape array of size aid into shape three by three. Sure, we can also reshape a multi dimensional array to a vector. Why way to do it is by means of the aforementioned reshaped function. Another way is to use the Raval function. Have a look. Here's our two dimensional array, B equals and P array. 123 four, 56 seven, eight nine. To keep things simple, let's bring out flying are two dimensional array. Now let's use the reshape function first, to turn it into a one dimensional array so into a vector and Peary shape going to reshape be array to Victor. So there's on the one dimension. Nine elements here is, and here's how we can do it with NP, revel function or its corresponding revel method and pay Raval be fine. The reshape and revel functions creative use. If we need a Cappy, we can use the flattened method, so be flatten, and this is a copy so these are views and this is a copy. It's also possible to add new empty dimensions or axes. To do that, we used the n p dot new axis cured as an index. Well, here we have a one dimensional array, see equals and p a range four. Fine. Let's print out Good. Now let's add one more dimension to the array. We can do it like so D equals. See and hear the indices, the whole of it and the new axes. So np new axes. Fine, let's print out. And when it does, it creates a new axis and new dimension. Now we have a two dimensional array with dimensions four rows. One call him. We can also use the new access as the first index, depending on where we want. The access to be added have, like e equals see and P new access. And I called him for the second index A. And now you get is a two dimensional array with one row and four columns
18. Merging numpy Arrays: well, we already know how to reshape race, how to add new axes, beauty mansions to them. But sometimes you may want to merge race into bigger a race like, for example, merge a couple of vectors into Matrix to these, and we can use the MPV stack and NP age stack functions, which stuck the arrays vertically and horizontally, respectively. Here's how the functions work. First, that's important. Um, pie. And now let's create two vectors. A equals and P array. 1234 Let's keep it simple again. The Equals and P array. 10. 2030 40. Okay, now let's tack them vertically. The these tack function takes a couple with the erased to merge as an argument so and pay these attack and the to raise in a tipple. A be I know what we get. A's The two dimensional array were these two race are stacked vertically Now, In the about example, the vector race became the rows of the newly created matrix array. Now let's see how they're eight stack function works, So np age stack. Okay, be This is what we get. Well, it emerges the to erase horizontally into another one dimensional array. But what if you want the vector a race to become columns of the newly created array? Well, we have to add another access to a Gerais, which we can do using the new axis cured. Have Luke and P Age Stack now the Triple A. In the end, this is Colin and and P new access and then be Colin on DPI new axes. And now the two factors are stacked presently as columns of the newly created Matrix. Naturally, the number of dimensions doesn't have to be changed when to raise our stepped Let's have a look at it following two dimensional erase merged. Together we can change functions. Let's create a vector array and reshape it into matrix around So C equals and P arrange 1 13 and now they should be reshaped into a three by four matrix. Okay, so here's our Matrix, and now another one d equals and P. R. Arrange 21 32 and also re shared to a three by four Matrix, while so he would have to. Ventress is too two dimensional arrays. And now let's attack the two matrices vertically. So N p, these tack and the triple with C and D, the two matrices. And here they emerge vertically without changing the number of dimensions. We can also stack them horizontally and p eight stuck. C d. Here they are, merge together. Alternatively, we can use the end pick and Katyn, a function for which we have to specify along which access the merging should take place. So let's merge e arrays vertically and pay Could Katyn eight. Now the two matrices to merge si and D and they should be emerged along the axis zero And this is what we get. We can also stack them horizontally and pay. Could Katyn eight the C and D matrices and this time along the access one so horizontally and here they are.
19. Arithmetic Operations: Well, now that we know how to create number, raise how to index them, how to slice them, merge, reshape and so on. Let's talk about some operations you can perform on them. Well, you can perform all the basic arithmetic operations on umpire raise. The operations are performed 11 wise, so it is important that the race have the same sizes and shapes. If they don't, it's still sometimes possible, but this will biddies cost in the next lecture. Now let's concentrate on equal sized arrays Max first create to raise on, which would then perform a couple of arithmetic operations. But the first thing to do is, as always, import the num pie module so import number by as in pay. And here the two arrays a equals and P arrange 17 Reshape 32 So it's a matrix. Here it is, and the we can create it this way. 7.2 in the first row, 4.5 in the second row and eight and three the third row. Here's our be array. As we can see, there are equal sized three by two, and now the operations First. The addition is very straightforward, heavily a flash B and this is the result. As you can see, the elements off the new array are the sums off the corresponding elements in the to raise . So one plus seven equals 83 plus four equals 76 plus three equals nine and so on. Now subtraction. It's exactly the same. So a minus. B. This time the elements are subtracted. So one minus seven is negative. Six and so on. Now multiplication a times B as before. Here the elements are multiplied like Sue one times seven equals seven or here have 18 because six times three equals 18 and so on. Well, one thing to note here is that this is different than matrix multiplication. Here the elements are just multiplied Adam and Wise and now to Division A divided by B. And when we get our floats, because floats are the results of two division. So as you can see the dinner time maybe promoted if the result can be represented within its bonds and now floor division, which returns integers a divided by B and this is the result. The first case. We have zero, for example, because one divided by seven using floor division gives us Syria well. Seven doesn't fit even ones into on, so the integer part of the result is zero about explanation. A ation a the power of B. Here's the result. So each element in a is race to the corresponding element in B, for example, who have 81 because three to the power of four is a one about module iss a ma jealous B so we can have the remainders off dividing the AMA's from a by the AMA's from be some of the model ISS. It's also possible to perform operations on a race and scholars. Then the operation is performed on this color and each element of the array. Here's some examples. Let's print our A array one more time so you can see it. And now let's at 10 to it. So let's at tend to each adamant of it. Here is the result one plus 10 11 3 plus 10 13 Answer Juan, And how about raising each element to the power of three? Well, A. To the power of three. So why did the power three is one four? The power of three is 64 so on when he performed the operation on to Raise and You Array with. The result is created in memory. Instead, we may want to assign the resulting array back to the first original array. You can use the regular Pythons syntax with augmented as seven operators being the preferable way to go. Some examples. So here's our air A one more time. And now let's add another aerated in place like Sue See equals NP Array. First row 12 Second Room 53 Sad Row 63 Here's our see array. Fine, and now we can do it. Life. So a equals a plus c. So now we're assigning the new resulting array the Wild, which results from adding these to raise to the original A array. Let's print out a why, as you can see now, a his change because now is the some of the original A and see. Instead of this, we can use the amended assignment operators. Now let's subtract two from the A array, the modified one. So there's one and assigned the result back to a will. Use an amended a Simon operator, like so a minus equals to hey, and this is the result, so too is subtracted from each element in a this a Tu minus 208 minus 26 and so on and the new array is assigned back to a
20. Broadcasting: as you learned in the previous lecture, operations and vampire race are carried out element wise. Have a look again for us. That's important. Um, pie and I'll have a look. A Equals and P array 123 b equals and P array tan 20 30 a plus b. So element wise one plus 10 equals 11 2 plus 20 equals 22 so on. This is possible because each of the arrays has the same size and shape. So what about this is this tale? Rays have different shapes. C equals and P array 123 d equals NP array First row 10 2030 second room 40 56 day. So this is a one dimensional array. This is a two dimensional array. Let's try to add them together. C plus D. It looks like this works, too, but not all a race of different shapes behave like this. Battery operations like addition, subtraction, multiplication and so on between two rays are only possible if the race can be broadcasted into the same size in shape. To start our discussion of broadcasting, which is the topic of these lecture, let's have a look at operations between an array and a scholar first, is this a basic example of broadcasting? Here's our example. Let's create an array e equals NP array 123 And now let's add five to each, adamant in it. So e Blast five and this is the result here. Broadcasting consists in expanding this color into an array of the same size and shape as the E array. In our case, the array has the shape three, so this color gets expanded to Vector 555 So now it has the same size, so effectively the operation above works exactly the same as this plus and P Array 555 This is what this color has been expended to to manage the size and shape of the array. Here's the result. Now, if the operation is between two arrays, it is only possible if the smaller array can be broadcasted, which means expanded so that it matches the size and shape of the larger array. Broadcasting can occur only if the axes of the to erase either had the same the length on a one by one basis, or if either of them has a length of one. How about an example. Let's create to erase a two dimensional one and a vector so half equals and P arrange 1 13 Reshape four by three. So this is our ticket financial array and then of actor G equals and P. Arrange Tan 31 Step 10. Here's our vector. Now let's add them together. F plus G works fine Because of broadcasting well, the smaller array G was expanded to match the larger array. Yes, So the G array worked as if it waas stacked vertically four times so that its shape match that of f you're for s So these tech vertically four times and the roads are the same. 10 2030 10 2030 10 2030 10 2030 in four hours. Here, broadcasting is possible because the length of the second axes columns is the same in both arrays. So I have three columns here and three columns here. Now the shape of F is four by three and the shape of G is free. Let's create another three demand Shal array with a shade four by Juan. So with the same length off the first access eight equals and P array 100 200 300 400 and in order to maggot at four by wanted Imagine Array, we have to add a new access. So on P new axes and here's our Asia ray. Fine. It's a four by one matrix. And now let's add F and H together F blasts age this time the length of the first accesses the same four. So here and after we have four rows and here we have four reps. The broadcasting works. And how about this? Let's create an array with shape six by four I equals NP. Arrange 1 25 Reshape 654 Here's our I matrix. Now the length off the axis, our sakes. Six rows and a 44 columns. According to the broadcasting rule, the other array must have one of the following axis length configurations. If you want broadcasting to work, it must be six by one or one by four. Let's try them both out First, a six by one array so J equals and P. Arrange 100 700 Step 100 Reshape six fi one. There's our J array fine, and now broadcasting should work because here's a kind of aggression is six by Juan. Let's try it out. I plus J. So as you can see broadcasting works now let's create an array with shade. One by four k equals NP Arrange 100 500 Step 100 reshape one by for here's Our K Array finds a two dimensional array. So, as you can see, No, let's add I plus K okay, it worse.
21. Mathematical Functions: Now let's talk about some of the medical functions. Non pipe provides lots of mathematical functions, which are backed arised, just like the arithmetic operations region means they operate element wise. They return new rays of the same size and shape with elements of the same type or another type, if necessary. There are really lots of mathematical functions, but just have a look at a neuro selection of them. Others will be used in the future when need arises. Let's start by creating a simple vector array on which we can demonstrate how the functions work first. That's important, umpire, of course. And here's a simple array. A equals NP array 12 Tan 20 for example. Here is and now let's demonstrate some functions first. Nps Q R T, which it turns a square root So and P S Q R t with a This returns The square is off. All the elements of these array one 1.41 and so on. Next N p e x p, which returns the exponential. So N p e x p. If a And here we have the exponential, then we have the logarithms in a couple of flavors like the natural logarithms and P log the algorithm in base to and pielach two or the longer them in base. 10 in Pielach Tan Have a week and p locked too, which means lug with him in base to of a and again this performed element wise. So the algorithm, in based to the first almond 10 to base of the power of zero gives us one. They have won because to raise the power one gives us two and so on. Then you have the trigger automatic functions as well as the universe. Hyperbolic and inverse, hyperbolic trick automatic functions. Here's an example with a sign of function. His values are in radiance. Have a look and p sin a So here, the sign of function. The next function is NP around, which is used to run numbers to given number of decimal places. Let's use it along with the result of the sine function so and p around and p sin. Okay, so the same result is here above, but this time they should be rounded to two decimal places. Decimals equals two and this is what we get. The same results rounded to two decimal places and, of course, the lose of other mathematical functions. You can read the bottom and documentation you need them.
22. Aggregation: well in this lecture, we're going to continue our discussion of number functions. This time we talk about aggregation. Non pipe provides functions for aggregation. They taken array as an argument and return either another array or is color. We can also use their counterparts implemented as methods in the ND array class. First, let's import Nam pie as usual. And now let's create a two dimensional array and then demonstrate some of the functions used for aggregation. So a equals NP arrange 1 13 Reshape four by three. This is our a r a. And now the first function going to talk about his np Some It sounds all the elements in the array and returns a scholar so and p. Som a well, this is the sum of all the elements in the array. Alternatively, we can use the method like so a dot some and the result is just the same. We can also aggregate over a specific access. Let's some the rose first just x is one. Now we're getting array with a sounds in a drew have like a some access equals one. And these are the sounds in a dro So one plus two plus three equals six. There's a first row 15 is the some of the elements in the second row and so on. And now the columns. Oh, some access equals zero. These were the South in the three columns here, here and here. The other functions and methods work the same way. Here's some examples. Let's say we need the average of all the elements. INGE Rome. You can use the main method. Okay. I mean, access equals one and this is the average the mean for each row. And now we need the product of all the elements in each column. So a fried access equals zero. Well, you have the products of all the elements in each column and now the standard deviation for each column. Hey, S T d access equals zero. This is the standard deviation for each car we can also aggregate. Cumulatively, here's how we can get an array off cumulative sums off all the Allens of the Array a come some cumulative som and here's the result we have one. Then you have one plus two, which is three. Then we have one plus two plus three, which is six and so on So these Adams are some cumulatively and here are the cumulative products by column. A cumulative product is the function we should years access equals zero. So by column and here they are one one times four equals four, four times seven equals 28 so on. We also have the MP max and anti men functions for the minimum and maximum value. Here are other minimum values in age row and pay men Oh, access equals one. These are the minimum values in each row. 147 10 one in this room 47 10 It happens to be the first album in this case, the M P argument and end the arm ox functions, on the other hand, returned the index of the minimum and maximum value respectively. How leg a our max 11. This is the index and weak the alleman with it Maximum value age finally to very frequently used functions and p all which returns true If all elements are no zero and n p any which returns true if any of the elements is known zero In case of our array, all elements are none. Zero. So both methods will return true how? Look. Oh oh, True, because all elements are non zero a Annie to, because there is at least one element, which is non zero.
23. Comparing Arrays: in these lecture will be talking about comparing them by race given to Nam pay raise. We can compare the element wise. What we get is a new array with Boolean values. We can use all the standard comparison operators like equals not equal to great Dan last Dan greater than or equal to less than or equal to. If the shapes of the rays are different, all the broadcasting rules apply some examples. First as important, um, pie. And now that's great. Too simple a race that we are then going to compare a equals and P array. One, three, six, 9 12 and B equals NP array to four six a 12 Fine. First, let's check them for equality a equals B and the result is force force to force to. So as you can see, they are compared element wise. One is not equal to. So I get force six. It's equal to six. So I get to now Inequality A is not equal to be this time We get true wherever the two elements in the corresponding arrays are not equal. So we got force here and here where the almonds are the same. Now let's use all the variations of greater than and less than operators. First A is greater than the so you have false because one is not greater than two you have true because nine is great and an aide. Now, how about this? A. Is less than the these works just the same you have. True because one A's last thing to here have force in the last example. Because 12 is not less than 12 now have a is greater than or equal to the and you have force force. True, true, True. So, for example, the last pair of atoms you have 12 and 12 12 a is greater than or equal to 12. And the first case we have false because one is not greater than or equal to two Fine and now we have a is less than or equal to be, and this is what we get to truth. Sue farce. True, for example, in the first example, we have true because one is less than or equal to two. In the third example, six is less or equal to six, so we got true. We can also combine the comparison operators with the aggregation functions and p any and empty all. Let's see if each almond in the air A is greater than its counterpart in the be arraigned and pay Oh, a is greater than the This is naturally false. So maybe there is at least one element in A with the same value as in B. So np Annie okay equals B to so there is at least one such element.
24. Conditional Functions: We can pick values from a race based on the condition to this, and we can use the functions and p wear and be select an MP choose. Let's have a look at them one by one. First, the NP wear function. It takes three race as parameters, the first of which is a Boolean array, which is actually the condition array. The function creates a new array, picking elements from the two arrays past as a second and third argument. Wherever the value in the condition array is true, the corresponding element from the second array is selected. Wherever it's false. An almond from the Third Array selected have a look. Let's start by importing imply. And now let's create two arrays from which elements will be selected. A Equals and P and Ray. 12345 six Good B equals and pay array 10 2030 40 50 60 for example, Fine and now the condition array. Let's pick the odd numbers from the first array, so conned equals a marvelous too is not equal 20 So this is for all the odd numbers. Let's bring the conditional array out. As you can see, we have true, false true falls to force. So this is odd. True. This is even falls this odd to and so on, and that we can use the conditional conned array to select all the elements from a for which the value in can't is true and from B for which its force have Luke and P. Where now conned. There's the condition, right and our NB arrays. As you can see, we have one from a because we had true in the condition array at this position. Then we have the element from the second Array because there was false at this position in the con array and I have three of the first Ray and so on. We can also create the race on the fly. Here's an example. See equals and P arrange 1 11 These are a C array and now that site. We want the squares off the elements that are less than six and square roots of the other elements so and pay where and here we can use the conditional array on the fly. So see is less than six this hour condition array. Now here's our first ray C to the power of To on the Second Array and P s Q R T of C. So there's the condition. So for each element and see which is last in six, choose this the Adam and Race to the second Power. If the element is not less than sex, choose this the square it of the element, and the result is so the first elements 123 four and five are less than six. So what we get is the squares of these elements. One squared equals 12 squared equals 45 squared equals 25 but then have six and more. And for these elements we get a square. It's so this is the square root of six is the square root of seven and so on. The next function is NP select. Let's define an array we're going to use here. In this example D equals and P array. Negative three. Negative one zero 24 And now let's use the NP Select function your days. This function takes two parameters. Ellis 0 1,000,000,000 condition. Raise your days L'Est with three condition arrays and Elise of race. Here's a list of the rays in the resulting array. We get elements from the array for which the correspondent condition. Is Matt having to get this example? Now? Let's run this code first so that you can see how it works. This is the result now. How does it work? Well, you're selecting. Here is the following we selecting the absolute values which is the first array off negative elements, which is the first condition. Well, we have to negative elements, Negative three and negative one. So for these two elements, we are selecting their absolute values which are three and one, respectively. Fine. Then we are selecting the squares which is the second array off elements less than three, which is the second condition last than or equal to three. So zero and to a less than or equal to three. And for them we're selecting the squares, So zero and four, respectively. Finally, we are selecting the Quinta pols, which is the third array off elements greater than three. This is the last third condition array over here. So only this element is greater than three. So what we get is a quintal of this Element 20. The next function is nt choose. It takes two parameters. Ah, list of indices. Analyst of a raise the indices determined from which array and elements should be taken. Here's an example. First, let's create free arrays. E equals NP arrange 1 11 Here's our E array f equals and P Arrange y No. One 1 11 g equals NP Arrange 1000 and one 1000 and 11 And here is And now suppose he won the 1st 2 elements from the first Ray when five elements from the second Array. Then again, one element from the first Ray and finally, two elements from the Last Ray. Here's how we can do it Using the Indus is off the race in the list of a rage, so N p choose And here is a list of indices. 00 So the 1st 2 elements from the first away, then five gallons from the second ray. So 11111 dan one Adam. And from the first Ray again zero and finally too adamant from the last ray to to. And now this is the first parameter and the 2nd 1 is the list of a race E yes, G. And this is what we get one to which come from first array than five elements with the secondary. He they are then one Adam and from the first away again and two elements from the last array.
25. Logical Functions: Nam by offers us a couple of logical functions in particular in theological and and Theological or and theological X or an amp. Illogical. Not let's start with the last one. We use the MP illogical, not function to element wise. Invert. An Array zero is interpreted as false and in non zero value as true. First, it's important empire. And now let's create an array of numbers. Now that's inverted and pay Logical, not a so we have. This is true and you have falls. This is false, so he'll have to is inverted. As you can see in the output, the values are inverted. We have true for zero values and false Finanziaria values. Another example, and p logical not a is less than or equal to zero. Now we have false for the values for which the condition is less than or equal to zero is met and true for the ones for which it isn't that this is because the values are inverted. The other functions work element wise Auntie raise. Let's create to rice demonstrating them. Hydrological functions work, so you have to erase B and C with bully and values. Let's start with the MP, illogical and function and P logical and and our to raise B C. Now we have true only at the indices at which there was true in both a race so true. True, true. First to force the amp illogical or function returns true. If there is true in a least one of the two arrays so and p logical or B C now you have to because we have to in both a raise you have True because there is true in at least one array here the same There is true in a least one ray. And here we have farce because there is force in both the race and theological accer returns to If there is true in one way, but not in both have like and pay logical accer b c So false because we have two in both the rays here and here we have true because there is true in one ray but not the other. And here we have false because there is false in both arrays
26. Random Numbers: in this lecture, we're going to talk about the random numbers. Mumbai provides a vast functionality for end of numbers. The functions we're going to need are in the AMP. Aranda module. The lots of them. We'll just have to get some first. Let's important EMP I. And now let's start with the NP random a random, which returns uniformly distributed. Float between zero and one, but not including one. Have a look and pay random random. We can pass an integral to the function. This will create a one dimensional array with as many elements as the teacher so and P random random six. Because he wants six Adams. And here are the random numbers between zero and 11 being included. We can also pass the shape of an array to create a multi dimensional array with random values. Have lick and P random, random and now the shape, Let's say five by three. And here we have the multi dimensional array we random numbers between zero and one. If you need a random integer use and P random, random, and let's find a random number between three and six. The letter being exclusive so and pay random Miranda and between three and six when we get as three, if you pass just one value, you'll get a random integer between zero and that value, which is also exclusive. Have a look and pay. Random Rand ain't three, which means between zero and three, and we got to. And now let's create a four by five array of random integers between 10 and 20 and P Random Rand ain't Tim to anyone because 21 is not included, and the shape of the oration before by five. Here it is. The MP Random rand function is used if you need an array of floats between zero and 11 being exclusive offer given shape. We just passed the dimensions along all the axis as arguments. Now let's create a three dimensional array of floats and P random rand four to three. Here it is. Random float numbers four by two by three is the shape of the array. Now let's use the end Corrente Brandon function again. We could use any of the other functions as well. If we execute the code multiple times, the result may be different Each time. Here have a one dimensional array of 12 Random integers between one and 100 have a big and P random rand. Ain't one. Why no one 12 shaved ender. These delays that we get now it will use the same code multiple times like so and execute it. As you can see, the results are different each time. This is because he's a random numbers. Now, if you want the numbers to be the same each time, we have to recede the generator to this and he should use the function and peer end them. Seed with an into your argument here will receive the generator with two different integers . Watch the results and P random seed. 31 print and P random rand ain't one. Why new on 12? This is what we get now. Let's try with a difference. He'd like 42. This is what we get. This is different than this because the seed is different. 31 42. Now let's use the first seat again. As you can see, this is exactly the same as this. This is because of the sea being the same. Also, we used the other's seed like so with the GATT, the same result as before. This is how it works
27. Set Operations: in this lecture we're going to talk about, said operations in Python. If we need a collection where all elements are unique, we use sets in Nam pie. We can also make all the elements in an array unique, and then we can work in it like on a sap. In order to make an array unique. We used the MP unique function. It also sorts the Iran. Here's an example. So let's start by importing numb pie. And now let's create an array with repetitive values like So now that's mega set of it. So B equals and p unique a be and this is what we get here. The values are normal, repetitive, they're unique. Naturally, we can also create a separate like this in one step, C equals and p unique. And here's the array, See, and here we have it. We can check whether the elements of an array are enclosed in another way. We can use the function NP in one D and passed the to erase to it. First, let's check whether Arabi isn't closed in C. These works a lemon wise, so we'll get true for the elements of B, which are in C and a force for those which aren't how big NP in one d be see. So the first is true because the first element of B, which is one, is also in C the last time. It is false because the last element of B, which is seven, is not in C. There are also functions for typical set operations. If you want to find the intersection of two arrays, we can use the MP Intersect one D function. This will return the elements we joined both a raise. Let's see which elements are in both B and C and P Intersect one D, B. C. 12 and three So 12 and three R B and in sick we can use the N P sec def. One d function to find the difference of two sets. The difference contains all the elements which are in the first rate, but not in the other. So the difference of B and C is and p Sad day for one D, B. C. Four and seven. These two elements are in B, but not in say so. This is the difference of BNC. Now let's check the difference of C and B and p Sad day for one D. C. B 59 So this is different because five and nine are the elements in C, which are not in B finally to find the union of two sets. So the elements which can be found in at least one of the South we can use the function and peeing in one D like so and p union one d be see. So here we have all the elements which are either in B or in C.
28. Non-Elementwise Operations on Arrays: Now, most of the functions we have been talking about up to now work in an element by element basis. Some, like the aggregation functions, either reduce a raise to scholars or flattened them to raise the fewer dimensions. But there are also functions in numb pie that operate on a race as a whole rather than element wise. And return transformed a race for the same size, although no necessarily of the same shape. The first function we're going to talk about is N patrons post. There also exists a method in the NDR, a class with the same name, and you can also use a special name just Capital T without parentheses. The function reverses all the axes. If used on a two dimensional array, it just exchanges there rose in the Collins. Here's some examples. First, that's important. AM Pie and here's a matrix array, a equals and P, a random rand int one 20 and the shape four by three fine This hour, a array with random integers between one and 20. Now let's transpose it first, using the transpose function and P transpose A. As you can see, the rose and the columns are now exchanged. So, for example, in the first row we have 832 and now this is the first column. 832 We can do the same using the transpose method. Have a look. Okay, transfers the same result. Or it's special Name T A. T. The same result. We have two interesting functions and p fleet are. Which means flip left, right and empty free beauty for flip up, down. We use these functions to flip and ray horizontally or vertically. First, let's pray the area again so that we can see it flying. And now let's see how these two functions work first horizontally and p. Flip left, right? A. So, as you can see, it's been flipped horizontally. The left column is now on the right, and the right column is now in the last. And now vertically and P flip up down a And now to get a say that the first throw is down here and the last row is up here. Another fashion is NP sort it source. The elements of an array along is pacified axes. Let's put the A array one would time to save better. Why and now let's sorted along the last axis, which is the default, so N P. Sort A. So as you can see, a drill is now assorted. And now let's specify another access and P sort. A access equals zero. So now it Colin is sorted. Now, the MP sort function returns in new array. If what we need is in place sorting, we should use this sort of method a sort. And here the arrays sorted in place.
29. The Dot Product: Well, as you know, we've been multiplied to matrix arrays. The multiplication is performed element wise, which is not Would real matrix Multiplication A's Let's see again how multiplication works . So let's import number I first and now let's create to factor a raise and multiply them using the standard multiplication operator A equals NP array three aid to B Equals and P Array four six one, Now a a Times B. As you can see, this is performed element wise three times four equals 12 8 times six equals 48 so on. If instead, you want to calculate the dot product of the two factors we should use the mp dot function like Sue and P. Dodd. Hey, be 62. Now let's create matrix erase and multiply them using the standard multiplication operator . These were Work Alum and Wise. So let's create our matrix array here like so that's putting out why. And one more de Okay, here it is. And now let's multiply them element wise. See times D. So two times two equals 45 times one equals five. Answer on element wise again, we used the n p dot function to calculated that product, so n p dot see de. And here we have the dot product of the two arrays. Matrix multiplication is only possible if the number of columns of the First Matrix is the same as the number of rows off the second matrix. Let's create to other race and multiplies and using the mp dot function. So here we have our first array that's pretty out and our second array fine here days now The First Matrix has three columns, and the Second Matrix has three rows so we can calculate the duck product and now a quick reminder of matrix multiplication. First, let's change. They sell to mark down for plain text. And now how? Look at this. You have our to erase e and F here we have the real numbers, and here we have the same written symbolically. So this is the first element in the first row. E one Juan. There's the second element in the first row A want to. So the first index refers to the road. The second index of the column and here's how the duck product is calculated. It was remember, just pas video and have their here. He would have the calculations and the results. So our new array resulting array shoot consists of four numbers 19 41 17 and 71. And now that's at another sad Lou. So let's go to edit mode that's hit, escape and now be for the next cell. And here we can use the mp dot function with our to raise e and F, and the results would be the same. So 1941 17 71. Well, alternatively, we can use the at operator for matrix multiplication. It also returns the dot product of two matrices, so hey at F and the result is the same.
30. Wrap-Up: now, in this course, we discussed the very basics of the number I module. There's much more you can do with this module, so make sure you have mastered all the topics covered in this course before you continue adventure with some pie and with scientific Parton in general, non pie places passion role in the scientific pilot and eco system it delivers at to which you can use in all the other scientific libraries, like pandas met Lip and tens of others, it's practically impossible to dive into scientific python without mastering the basics of numb pie. In this course, we're talking about the development tools like the iPod and console this spider I D. And first of all, the Jupiter Notebook Web application. These are the tools you'll be most probably using when working with some pie and the other scientific modules in the future so they worth knowing. There it is cast down by a race, we learn how to create them and how to use them. We discussed all the different operations and number A raise and the functions none primordial provides. I hope you like the course and, first of all, fund useful. Looking forward to seeing you in one of my future courses. Good luck