transcribe

Learn NumPy - Complete Course for Beginners with Craig Dennis

Treehouse · 2h 17m · transcribed Jul 2026
More from Treehouse Business
𝕏 Share ▶ YouTube 📥 PDF 🤖 .md

Section Insights

# 0:00

Introduction to the Course

What is the purpose of this course?

The course introduces Python's NumPy library, essential for data analysis, scientific computing, and machine learning.

  • NumPy is critical for various applications in Python.
  • The course provides hands-on examples to understand NumPy fundamentals.
  • Learners are encouraged to control their learning pace.
# 15:17

Understanding GPA and Lists

How can we use lists to store GPA scores?

The instructor demonstrates creating a list of GPA scores, emphasizing the mutability of lists and the ability to append and insert elements.

  • Lists in Python can store multiple data types.
  • You can append and insert elements into lists dynamically.
  • Understanding how to manipulate lists is fundamental in Python.
# 30:35

Array Indexing and Slicing

How do you assign multiple values to an array?

The instructor explains how to use slicing to assign multiple values to an array in a single statement.

  • Slicing allows for efficient assignment of multiple values.
  • Understanding zero-based indexing is crucial for correct assignments.
  • Slicing skills will be practiced throughout the course.
# 45:53

Adding Dimensions to Arrays

What are the methods to add a new dimension to an array?

The instructor shows how to create a new array with an additional dimension using NumPy functions.

  • Arrays can be multi-dimensional, enhancing data representation.
  • Understanding array shapes is important for data manipulation.
  • NumPy provides functions to easily manage array dimensions.
# 61:10

Identifying Values in Arrays

How can we filter values in an array?

The instructor demonstrates how to identify values in an array that are less than a specified threshold using comparison operators.

  • Comparison operators can be used to filter array values.
  • Understanding boolean indexing is key for data analysis.
  • The ability to manipulate and analyze data in arrays is powerful.
# 76:28

Slicing and Copying Arrays

What happens when you slice an array?

Slicing an array creates a copy, allowing for manipulation without affecting the original array.

  • Slicing returns a copy of the array, preserving the original data.
  • Understanding how to slice arrays is fundamental for data manipulation.
  • Negative indexing allows for reverse traversal of arrays.
# 91:46

Broadcasting in NumPy

What is broadcasting in NumPy?

Broadcasting allows operations on arrays of different shapes, applying a scalar value across all elements.

  • Broadcasting simplifies operations on arrays.
  • Understanding broadcasting is crucial for efficient data manipulation.
  • NumPy's ability to handle different shapes enhances flexibility.
# 107:03

Array Operations and Vector Math

How do arithmetic operations work with NumPy arrays?

NumPy supports element-wise arithmetic operations, allowing for vectorized calculations.

  • Arithmetic operations are performed element-wise in NumPy arrays.
  • Understanding vector math is essential for data analysis.
  • NumPy's overloaded operators simplify mathematical computations.
# 122:21

Using Functions for Data Analysis

How can we use built-in functions for data analysis in NumPy?

The instructor explains how to use functions like sum and mean to analyze data efficiently.

  • Built-in functions abstract complex calculations, making analysis easier.
  • Understanding how to apply functions to arrays is key for data insights.
  • NumPy provides a wide range of statistical functions for analysis.

Transcript

0:00 hey everyone i'm gil an instructor at treehouse where you can learn the in-demand technology skills needed to land your dream job we offer thousands of videos created by expert teachers on coding designing and much more if you'd like us to publish more free high quality courses like this please like and subscribe check the description for a link to download and work with all the project files used in this course happy learning

0:34 hi i'm craig and i'm a developer in this course we're going to be taking a look at python's wonderful data library numpy you'll find numpy in all sorts of applications and therefore it's fairly critical that you have an understanding of its fundamentals it appears in every direction you may have in python should you plan to get into data analysis or scientific computing or even machine learning you're gonna bump into numpy and that's what this course is all about

0:58 it's an introduction i want to introduce you to the library early on we'll walk through hands-on examples that will give you a great introduction to the library its main concepts and the surrounding terminology when you've completed the course you'll have a great foundation and you'll know where to turn when you need more specific information but before we get started let's take some time to make sure that you're familiar with your learning environment first off there are

1:21 some prerequisites to this course and i'd love for you to make sure that we're on the same page about where you are in your coding journey there's speed controls on the video player so please feel free to speed me up or slow me down pause me make me repeat myself whatever you like i won't mind at all you are in complete control of your learning a quick reminder there are notes attached to each video this section is usually filled with additional information that will enhance your

1:46 knowledge should you want to dive deeper into related topics get in the habit of checking the space and i'll do my best to remind you when i've put info there that you just have to see one more tip remember that there is a community of fellow learners also taking this course i encourage you to lean on each other if you have a question make sure to ask it our community is very friendly and approachable also remember nothing helps to submit your learning better than answering a question

2:11 make sure to check out the community throughout the course and see if you can help out a fellow learner we've established that numpy is extremely popular in many fields of the python landscape but what is it exactly now numpy is short for numerical python it deals with numbers so that makes sense all those applications that i mentioned would indeed need to use numbers and math equations in some shape or form but as someone who is actively learning python you might

2:38 cleverly state wait a second i can use numbers and do math just fine and play an old python what's the big deal why do we need this that's a wonderful question and the short answer is that numpy is much faster than the straight python approach no matter how great of a coder you are it leans on a paradigm which we'll get into here shortly called array programming it completely removes the need to loop over your data which speeds things up tremendously

3:04 numpy also provides additional mathematical abilities not available in standard python many numerical concepts have been abstracted away for you and provided as functions and chances are you probably aren't going to use all of those helper functions however the applications that you're building you know the ones that are relying on the library they most likely will numpy exposes concepts from linear algebra matrix multiplication fourier transformations and many more themes that you might remember from your math class if math isn't your area of study now just a heads up

3:36 it's totally fine if math isn't your jam it really doesn't need to be that's kind of the beauty of these abstractions you'll use them when you need them my advice is just to stay focused on where we're headed and don't let the shiny tools and terms distract you too much i'll point out what i think is important at this part of your learning journey now believe it or not that was the short answer to the why would you want to use numpy question the long answer is going to take me

4:00 a couple of videos to get you to see the beauty that is numpy one of the more challenging tasks of picking up numpy is simply just remembering how to use the objects that it provides so i was thinking of facing that challenge head on let's do this let's build a jupiter notebook together and then you'd have a reference and we could kind of treat it like a cheat sheet you could then quickly glance at it or even practice some more with the data sets that we build up sound good speaking

4:26 of practice that gives me a great idea have you heard of the movement called 100 days of code it's a wonderful idea that a lifelong learner alexander callaway came up with the way it works is this you publicly commit to coding at least an hour a day for 100 days you post about it on social media usually twitter and you hold yourself accountable it's wonderful for learning steady practice will strengthen your skills it creates a great habit of learning

4:52 it also seems like a great way to explore the numpy array data structure we can use it to track and analyze our time the only downside i can see is that it might create some pretty meta tweets if you are committing to learning numpy and creating a log to help track and analyze your 100 days of code in numpy reporting on your learning is going to create a tongue twister of a tweet you'll figure it out so what are we waiting for what do you say we get things all set up

5:19 there are a couple of ways to get things installed here but by far the best way to experiment with a package in my opinion is by using anaconda if you haven't heard of anaconda it's a distribution of all the popular python data libraries i'm actually going to use a smaller version of it called miniconda but either will do we offer content on how to get it installed if you don't have it already it's in the teacher's notes

5:39 if you don't have miniconda or anaconda installed why don't you pause me and get that installed and then come follow along let's get things cooking so here i am at my command prompt and i'm going to make sure that i have conda installed so i'll type conda dash dash version awesome i do okay now i'll create a directory called intro to numpy and i'm going to change to that directory so cd intro to numpy and now i'll make sure that i create a new environment so i'm going to say conda create

6:17 and i'm going to name it a hundred days and then what we want to install is numpy and jupiter you just kind of list them off here the things that you want so we definitely want numpy and jupiter and this will kick off and set everything up for us then conda saves environments to make sure that things are always at the right version by providing a virtual environment so i'm gonna let this go it's gonna take a little bit see you when it's done and there

6:47 we go everything's all installed awesome so i'll activate our new environment so we'll say conda activate a hundred days oh and i got a big error message here let's go ahead and i'm going to grab this here this echo we're going to echo into our profile.d file here on mac let's paste that here so now that i pasted that into the profile d i need to restart my bash so i can say

7:23 profile and now i should be able to say activate a hundred days awesome and now i can open up our jupiter server so i'll say jupiter notebook and that po popped open a brand new window which i'll bring over here to us and i'm going to choose over here this new we'll do a new python 3 notebook

7:54 and i'm going to come up here and i'm going to rename this to introduction to numpy okay and i want this first cell here i'm going to make this first cell markdown and i'm going to write heading 1 of introduction to numpy and we'll just say learning numpy so i'd like to repeat that i'd love for you to follow along and make your own notebook i'll give you mine when the course is over so you can have all of my notes but please feel

8:26 free to make your own comments i find that when using these notebooks it helps to capture your thoughts to review later i really like using these for cheat sheets so we can actually run this cell and enter the next one by choosing option enter on a mac so option enter and just a quick heads up i love keyboard shortcuts you can pick up some great productivity by learning them so open the list here and kind of type what it was that you were looking to do so we were looking to run that cell

8:54 so if i type run and we'll see here we have run cell and insert below that's what i did so this is option entry this will look different if you're running this on windows pretty cool right okay so the new cell that was created here is python by default all right so it's code i want to make sure that we got things installed correctly so what i'm going to do is i'm going to import numpy now

9:16 as it turns out data scientists are just as lazy as programmers and don't like typing more than we need to so a very common way to use numpy is to import it as mp so you say import numpy as mp and that will allow you to skip some unnecessary characters we don't want to type more than we need to where of course that stands for numpy but i like to think of it as no problem and that's

9:46 because when we're done here numpy will be no problem like most great libraries the numpy module exposes its dunder version so we'll just write that here let's put that in the same cell here we'll say mp dot under under version and remember in jupyter notebooks when you run a cell the last line it will show its output so here we go and you'll see that i'm running version 1.14.5 now you are most likely using a more current version than i am and there shouldn't be any breaking

10:16 changes for this course between your version and mine but that said i can't predict the future yet so therefore if there are any problems i'll make sure to list those in the teacher's notes so please take a moment right now to check those out i don't want you to have any problems i want you to have no problem np with numpy in p all right now that we have our environment all set up correctly let's dive into learning the most critical data structure of numpy the

10:44 array arguably one of the most important things to get familiar with in numpy is the array data structure that it introduces arrays are around in most programming languages so you've probably heard the term floating around before now don't worry if you have it you'll be super familiar with the concept here shortly python actually has an implementation in its standard library arrays are a way of organizing your data an array is a data structure that allows you to store

11:10 multiple items in a single variable which yes wise pythonista sounds an awful lot like a list doesn't it but there are some crucial differences between a list and an array the array is much more restrictive than a list which i realize doesn't sound like a great selling point but in fact it's actually these restrictions that make arrays the go-to solution for most python projects involving data a list as you know can contain just about anything and by anything i mean the type of

11:39 elements in there don't matter right a single list can contain booleans and strings and any random old object arrays aren't like that every single item in the array must be of the same data type that's the first major difference between the list and an array now the second one is that the array's length cannot be changed its size is immutable you can't add items to the array or remove from it you can change the value of individual items but the size cannot be changed

12:07 and it must be defined when it's created when we work in these higher level languages like python we don't really need to think about how things are working under the covers that's because the language does a wonderful job of abstracting that away from us right what do you say we take a peek behind the curtain real quick when i create a new variable named age and set it to say 29 i wish what really has been abstracted away is that python has to go to the memory on the

12:37 computer and find some free space to store that number storing that number is actually another abstraction isn't it it's really just binary right it's a series of ones and zeros that gets put in there and then later when we go to access it again our variable name references that memory location so it can be used to go to and read that value from memory and because it knows the size required for its data type it can grab the right version of ones and zeroes to have it

13:03 represent the original value in our program 29 i feel like i have aged a year just explaining that there are lower level languages like c where you actually have to do all the memory management you have to go find the space yourself put the value in there and clean it up when you don't need it anymore now i'm certain that you could totally do that if you had to but this work has been abstracted away from you so you can focus on more important things

13:28 one thing you probably don't think about often is how awesome these python lists actually are you create them you append stuff to them you move stuff you insert stuff that stuff can be any size so every time something is added the same flow of finding the proper space with enough room to hold that data needs to be located and there's even more to the list abstraction here each of those whatever size objects all can be iterated through or accessed by index it's pretty impressive when

13:56 you stop to think about what we've been taking for granted there's a lot of effort that is hidden behind that abstraction to make things seamless that effort actually does have a cost namely speed it's a lot of overhead and it wouldn't be needed if only you knew how much space each element required as well as the total number of elements that would always remain the same hey those restrictions sound pretty familiar don't they those are the restrictions i was

14:24 talking about that arrays have when the array is defined or declared the only type of element that it can store is defined as well as how many elements will ever exist therefore the space to store the whole array structure is known at creation time what this does is it allows for each element to be stored next to the following one the elements are contiguous or one right after the other with no space in between them this makes finding exactly where an

14:52 item lives in memory a very easy math equation much quicker than accessing an item in a list let's go build an array okay i'm going to give us a little more space i'm going to click view and i'm going to toggle the header that feels better let's start by building a list that we can use for a quick refresher so i want to store some floating point numbers okay well how about we store my high school gpa scores for those of you out there outside of where i grew up which is the

15:25 united states gpa stands for grade point average and we are or at least at the time a little over obsessed with them now it's an average of all your grades in all subjects on a scale from 1 being the lowest to 4 being the highest okay so let's declare a new list called gpas as list and we'll use a hard bracket literal for our list i'm doing this for high school now this

15:58 is the part of school before college it's called secondary school elsewhere okay so what did i earn i don't remember really i've forgotten it because i didn't really use these things so our brains tend to forget information that we don't use by design well i know i started off strong so i'm going to give myself a let's give me a 4.0 and then let's see math started to get a little weird remember geometry and whatnot oh man in

16:32 chemistry i must have dropped a bit let's do 3.2 well shucks i i'll give myself some more precision there so let's do 3.286 that's better and then we had some trigonometry it was still pretty rough but i started building out that math foundation so let's say 3.5 and then let's not even talk about seniors physics and calculus okay fine i'll add it

17:02 and i can because a list size can be mutated right so i can just append to it let's say for.0 i did have a hard time that year with calculus but eventually it all started making sense once i got that graphing calculator working and i haven't thought about that sweet ti 82 since then i'm gonna make a little note here about this list too so we'll put a comment in here we'll say can have elements appended to it so on top of appending i can also insert into the list wherever

17:41 i want so and also we can have multiple data types in this list right so let's do gpas as list dot insert because we can put them anywhere and at the first position we're going to insert whatevs because that's a string in there so that's kind of strange and i can pop it right out right so i can say i can't have items removed so we can say gpas as list dot pop one and i'm gonna run

18:15 this and we'll see that we got back this last line here this pop whatevs is right so we can stick whatever in there so let's take a look make sure we got everything looking like we want awesome now let's create a numpy array a common way to create an array is to pass the array function an iterable and we have one of those so let's go ahead we'll make a brand new array and we are going to call it gpas equals numpy dot array gpas as list so now that we have one let's

18:57 see what we can do with it one of my favorite things about jupiter notebooks is that it lets you peep the documentation on an object if i just say question mark gpas nice so this is an indie array some documentation here here's some parameters here's d type the data type and here's some attributes for it so detect the detail describes the format of the elements in the array awesome so let's just go ahead and see what we have going on here so if we say gpas.dtype

19:30 float64 64 there stands for the number of bits remember the ones and zeros that are required to store the data type oh speaking of which looks like we also have item size the memory use of each array element in bytes so we can say gpas dot item size eight eight bytes that makes sense right eight bits are in one byte and our data type 64 takes

20:02 64 bits so eight bytes is 64 bits eight times eight all right so what else do we have in here size that's great one so let's take a look so we have gpas.size four and numpy does a pretty good job of being pythonic which means most objects just work like you think they should like if i wanted to know the length i should just be able to use the len function right so we could say lin of gpas and while not the best naming

20:38 we can also get the number of bytes that are required for the data so if i say gpas.inbytes we'll see 32 which of course is just the length 4 times the item size which is 8. so 32 but it's still nice to have okay i just threw a ton of information at you so let's go ahead and take a quick breather but before we do that let's do this let's do

21:11 a little exercise of writing up a nice summary you know try to capture our train of thought we found that reflecting on what you just learned will help you when you come back to it later i'm gonna come up here so i'm gonna get in command mode by pressing escape see how it's blue i'm gonna come up here and i'm going to go right above this gpa's list here and i'm going to make a new cell so i'm going to make a new cell above this so a i'm going to press the a key there's

21:40 a new cell above it i'm going to press enter and i'm going to switch this to markdown and i'm going to write down some notes here so i'll say pound pound for second heading we'll say differences between lists and numpy arrays and during the break i'm gonna do some reflection and i'll share with you what i jotted down in the next video but i'd like for you to give that a shot too treat it free form just jot down some thoughts and like i said i'll share mine with you in the next video

22:15 sound good okay so do that and when we come back we'll start our hundred days of code study log so how'd you do with your reflection now here's what i came up with so my first point is an array's size is immutable you can't change it right so you can't append insert or remove elements like you can with a list and we showed that down here all of an array's element must be of the same data type i went and did a search for the different

22:43 data types that are available and i made a little link here i like to use those as bookmarks and we'll actually use this one here just in a bit and then finally a numpy array behaves in a pythonic fashion you can use lin my array just like you'd assume awesome how'd you do that feel good all right are you ready let's build out our study log we should track how many minutes we studied for each day now we know that there are exactly 100 days in the challenge

23:10 and since we can't add or remove entries we know that the array that we create will need to be 100 elements now before when we created our array we did it from an iterable right remember we did this np array and we passed in this list here but in this case we don't have an iterable we don't really have any data but we do know that we eventually will this is a common enough problem that there is a provided solution what we want basically is a

23:39 hundred element array where each element will represent the minutes that we coded each day and we want each of those elements to be initialized with the value of zero lucky for us there's a helper method called zeros that does just that so let's do it let's create a new array called study minutes and it's right off of that package so mp.zeros and the first parameter is the shape or size so we want a hundred awesome and if we look at our study minutes array we could

24:14 do that just by putting it right underneath here we'll say study minutes and there we go a hundred elements 100 zeros and you'll see that these zeros have this dot here and that's showing that these are floating point numbers now one thing that we can do with a jupiter notebook is to get some additional information and we can do that using the whose command h-o-s this magic command whose if we do that we can find the study minutes array and we can see that it's 100 elements and

24:44 it's of type float 64. and that's must be what the default is happening right so it takes 64 bits or 8 bytes to store each of those but we know something about these values don't we we know that there are 60 minutes in an hour and that there are 24 hours in a day and therefore we know the max value could only be 1440 which really isn't too large of a number let's go ahead and use that link from before and see what other data types

25:15 are available so let's come back up to these notes i'm gonna go ahead and click click this okay so these are the different ranges of values that things have and we're at float 64 right now so double precision float there's a sign bit we don't need all of that it's a lot of precision we just need minutes up to 14 40 not portions of a minute so we don't need a floating point at all so we're probably up in this integer area up here right so integers right those are those are whole

25:45 numbers and in fact you can't study negative minutes in a day so we need an unsigned integer that will be always positive see these are these are these go negative we only need zero forward right and so we need 14 40. so this first one this u inst that's again unsigned integer of 8 bits we can probably get it here right because this 1440 is in between here so we can use this uint 16. so the data types are available as np dot the name of the thing afterwards so

26:20 we can we can use that so let's flip back to our example we're down here at our study minutes and let's go ahead and we can put in our data type is mp.uint 16. and now remember this was at 800 bytes so it took 800 bytes before so let's go ahead and let's specify the data type let me go ahead and run this one more time and you'll see the dots are now gone now if i rerun this who is with control enter you'll see that it's now 200 bytes

26:57 now at this time what we did is probably a little bit of premature optimization we only have 100 entries but i want you to imagine these arrays as enormously large they tend to get that way as you work with larger and larger data sets constraining to the proper type can save a lot of space and in turn speed by specifying a data type to meet your needs i've started this challenge already and on the first day i plugged two and a half hours into it

27:24 now you only need to do one hour each day but i was super into the challenge and i hope you will be too so two and a half hours is 60 plus 60 120 plus 30 150 okay so i'm gonna set my minutes for the first day so an array element can be set by its index just like lists and just like lists the indices are zero based right remember the first element is zero the second is one and so on

27:51 so let's do that let's set this we'll say study minutes zero and we'll set that to our 150 and you can retrieve the value also by using the index so we'll say first day minutes equals study minutes zero and if we take a look at first day minutes see that 150 came back that's interesting though isn't it we know that when we put our value of 150

28:29 when we put this in here we know that it got coerced or transformed into an unsigned integer 16 right so we know this is a unit 16 but this looks like it's just 150. why don't we take a deeper look at this so let's say type of first day minutes and we'll see what comes back nice it's just cleverly wrapped in what is known as a scalar data type here you see that the scalar data type is uint16 which is what we declared each of the elements to be scalar is a term that comes

29:06 from mathematics and for our purposes right now it can be thought of as representing a singular value now you'll hear the term scalar thrown around for values that are a single element and the term vector for those that are multiple you'll also hear arrays and vectors used interchangeably now this naming comes from their common mathematical use cases which we're going to touch on here in a bit for now though i want you to just know that the single values pulled out of a numpy array are

29:32 scalar and wrapped in their specific data type object these scalar objects provide the same api as arrays this is so that scalar objects can interact with other arrays easily again don't fret too much about this we'll get into it as the course progresses but check the teacher's notes for more information on scalars if you're interested let's go ahead and fill in the second day of the challenge i was able to sneak in some code after i got my kids to bed

29:59 i've been working on this microcontroller project and i was able to get some progress on it and the challenge encouraged me to do it so i spent about an hour on it okay so how would i track that how would i go about doing that so i want to put 60 minutes into the second day of the challenge hey how about you give that a shot you know just to make sure the stuff is sinking in so i'll do it to

30:25 do here and you you do it so to do add 60 minutes to the second day in the study minutes array pause me and give it a go and then after you get it unpause me and i'll show you how i did it are you ready pause me okay so i can't tell you how many times this bites me i said second day so i feel like it should be index two but it isn't is it it's actually index one and i'm gonna set that to 60.

31:03 now you might be wondering if you can assign multiple values to an array in a single line in a single statement if you remember your collection slicing skills they work here too so i've got four more days of data to enter i kept plugging away and let's see i had 80 minutes and on day three and then i squeezed in another hour of 60 and i only got a half hour on day five so it doesn't actually meet the challenge criteria of doing an

31:30 hour a day but you are allowed one day of wiggle room so i didn't break the challenge so i kept going and i made up for it and i got 90 here so i want to add these into the study minutes array and i want to start at the third day so we'll say study minutes let's start at the third day so again that's two there are four of them so i want to go up to the sixth day so the way that

31:54 slices work remember is they are exclusive it does not include that seven so we're going to say 2 to the 6 so that's not the 7th day there we go and that should do it that will set it and then if we go ahead and take a look at it afterwards we say study minutes give that a run we will see boom there they are so we got 150 on our first day 60 on the second

32:21 and here's the values 80 60 30 90. awesome if your slicing muscles are out of shape don't worry we'll exercise them throughout this course and you'll be super fit when we're done well one thing we didn't go over earlier when we ran this jupiter notebook whose command is that you'll notice the data type here is in the array now this in d it stands for in dimensional meaning the array can have many dimensions which is to say that these arrays can be multi-dimensional

32:52 which i realize sounds a lot like a science fiction term we'll get to what that means exactly right after a quick break hey during that break why don't you do a little reflection specifically surrounding what we went over about data types and choosing the right one and how it can save space i'm going to put my notes in here right above this call right above this call to zero so i'm gonna press escape i'm gonna get back into command

33:21 mode i'm gonna press above then i'm going to get this into markdown there's probably a keyboard shortcut for that to share about that so i'm going to say about data types and again just like before i'll share mine right after the break take some notes about what we learned here see you soon multi-dimensional is such an intimidating sounding word isn't it it sounds futuristic and outer spacey i mean what does many dimensions even mean especially in

33:52 the context of an array well the answer is kind of boring in comparison to how cool it sounds if you think about what we've been doing so far with our arrays we've basically been building a container where each slot represents something for instance in the grade point average example each element represented a single year of school so we could say that this is the year dimension now let's imagine that we wanted to track every student in my graduating class now of course we

34:17 could add a separate variable for each student but wouldn't it be nice to store that all in the same variable well you can what you do is you add a new dimension the student dimension now we essentially have rows where each row represents a student and each column here represents a year and would you look at this we have two dimensions and really a two-dimensional array is just an array of arrays right i can access the student i want like the third one here and then i could

34:47 select which year i want i want the sophomore or second year there's a term that is used to discuss how many dimensions an array has this is called rank so this gpa example is currently rank two now fun fact about two dimensional arrays you remember how single dimension arrays are often referred to as a vector well a two dimensional array is referred to as a matrix now remember these are called nd arrays and again the n represents

35:17 any number because you can have as many dimensions and ranks as your heart desires like we could add another dimension of school where each school had all of their students so that's 3d and most likely you'll need to wear these glasses to see that sorry that's a bad joke but see now we have an array i'll choose the first element and that is our array that contains arrays all right not as intimidating as it sounds but i bet you feel like you need some practice to

35:44 fully grock it right let's do it so first let's review our notes so here's mine about data type so by choosing the proper data type you can greatly reduce the size required to store objects remember we saw that and again i put the link here just to jump off the data type page whenever we need it to review later i think that's handy bookmarks sort of data types are maintained by wrapping values in scalar representation remember when we pulled that value out of the array it still knew the size

36:13 that it was even though it kind of looked like it didn't and it was a singular value which is scalar np zeros is a handy way to create an empty array filled with zeros like we did right here so we did this and we pushed the data type of the you unsigned integer 16. awesome okay so let's return to our gpa example which is here i'm going to click in here put it in command mode and add one below so b and what i'd like to see here is a new array we will make

36:44 students gpas so it's a list of students gpas and we'll make a multi-dimensional array so we'll say mp.array and we're going to pass in an iterable again and we are going to make this iterable just be a list of lists so first we'll push mine through here so we have this copy that paste this here and i'm going to do a comma and i'm going to add another list so let's add another student her name is vlada she struggled at first english was not her first

37:18 language but then she totally nailed it so she had a 3.2 her first year and then she started getting a lot better 3.8 and then at the by the end was just sailing 4.0 4.0 awesome and let's see one more let's add quasi he was on fire all through school he started with a 3.96 he got a 3.92 his sophomore year then he got he ended up with 404 4.0 4.0 awesome so let's make sure that we grab the right data type for this so right now the second parameter

37:52 we've been leaving empty let's say mp dot and then what do you think that was let's see let's use this this link one more time we'll click this oh i already have it open here in a tab so this data type let's say we it's at 64 we definitely don't need that we should be totally fine with just this this float 16. so let's use float 16. so we will build our student gpa with a float 16.

38:24 and then let's take a look at it too we'll say students gpas so this is really just an interval it's a list of lists so each element of that list is another list okay list of list multi-dimensional list so let's go ahead and take a look at it awesome and it looks exactly like we want it's an array of float 16 and it has all of the values there now it's possible that we would have run into a bit

38:53 of a precision error but we didn't we haven't run into that here but just in case because we did set a data type it might change the precision check the teachers notes for more information on that so we now have a two dimensional array right we have rows and we also have we have columns right we have these columns here you can always look at the property on an array to see how many are there and we have dot in dim for number of dimensions

39:27 see that it has two if we wanted to see how many elements are in each dimension we can actually view that that is exposed using what is known as shape so we can say students under gpas.shape this is saying three by four and there are three rows and four columns each element in this tuple represents the length of each axis so that's another term that you'll see used to describe

39:57 dimensions the plural for axis is axes not like what paul bunyan had a bunch of he had axes these are axes a-x-e-s so in our case the first access is students and the second access is years axes are zero based so access 0 is 3 and access 1 is 4. now one thing that might bite you if you

40:28 aren't careful is that if you use the size property so if we say students gpas.size it's going to tell you all of them not just the first dimension if you want to see just the first dimension you can still use lynn and that will just show you how many students there are three there's also a property that we can peek at called item size so again students gpas dot item size and that shows you how many bytes are being used for each item

41:01 which means now we could calculate how much space we're taking up if we did studentsgpas.itemsize times studentsgpas.size we're taking up 24 bytes which lines up with exactly what you would see if you were to use the who's command so say whose and then if you follow a type in the array it'll show us all the indie arrays so here's the four by four this is the singular one that we had and look that was 32

41:33 bytes and here's three by four and it's 24 bytes it's already smaller data type savings for the win right this whose is a jupiter notebook special command but you could also grab this information and any information of a numpy object using a function named info np.info and we can pass in students gpas and if we take a look we can see there's the shape 3.4 there's our item size and here's the type and some more information all right so let's access some things so if i wanted

42:07 to get access to the third student's record i could just do this i could say students gpas and that is this the third student right that's quasi's grades and see how that returns me an array so of course if i wanted to i could just chain off of it right because it is an array like let's say i wanted to get the last year here so i could just get this last year this last four here so i could say students gpas

42:42 two so that will get us this the student there and then i just get three and it should return back four awesome this is just one way of accessing this value in the two-dimensional space and remember this 2d or two-dimensional example is synonymous with the term matrix whoa sorry for making multi-dimensionality seem a little less futuristic than you probably anticipated it still sounds cool though right so make sure you drop it when

43:14 someone asks what you're learning oh you know just coding in a couple dimensions i do hope it's pretty straightforward and we'll get lots of practice working in in dimensions through the rest of this course now that you've got a handle on the main data type and most of its terminology let's go ahead and wrap up this first stage we'll go deeper in the remainder of this course and i'll show off some great shortcuts as well as

43:34 how to use these powerful multi-dimensional arrays to your advantage for now though why don't you make sure you reflect a bit on multi-dimensional arrays and add some thoughts to your notebook and please remember to take a break and let all your learning sink in you deserve it see you in a bit welp it happened to me i had committed to code an hour every day for the 100-day code challenge and sure enough i didn't make it i missed two days in a row thanks to a netflix

44:06 binge we've all been there and sure enough though technically i broke my commitment i was pretty bummed about it i was really enjoying the challenge now the good news is you can start your challenge over without losing your previous wins what you do is you just start a new round now if you started the challenge you might have seen people using that syntax in their tweet r1 d6 which stands for round one day six but that brings up an interesting point how would we

44:32 represent that in our study log array currently each of our columns is used to represent a day remember it's a 100 element long array filled with zeros so how could we also track rounds you know what you're right we just need a new dimension don't we good thinking come help me out with this so i can get back to studying before we get to upgrading our study log i'm going to review my reflections of multi-dimensional arrays i feel like i forgot

44:59 a bunch of the stuff while i was binging that netflix series good thing i wrote it all down for my own recall so the data structure is actually called an in d array representing any number of dimensions that's where the nd comes from right and arrays can have multiple dimensions and you declare them when you create them cool dimensions help define what each element in the array represents so a two-dimensional array is just an array of arrays like multi-dimensional lists

45:29 rank defines how many dimensions an array contains and shape defines the length of each of the raised dimensions remember that was like 3 4 that we saw right and each dimension is also referred to as an axis and they are zero indexed multiples are called axes even though it looks like paul bunyan's axes and a two-dimensional array is also known as a matrix awesome i am refreshed and ready to go now there's a couple of ways to add a new dimension let's explore one of them

46:03 let's get back down to where our study log is here we go here's our study minutes array go ahead and let's get rid of this where we print it out one more time and run that one more time there we go so let's make a brand new array which consists of our array and a new row of zeros so we could do that pretty easily we'll just we'll reassign we'll relabel we'll remove the

46:34 study minutes label from the other one and put it on this new one we'll say np.array and remember arrays accept iterables and our study minutes is iterable so we'll say study minutes here so that's an array of an array so we'll just do np 0s 100 and we'll do mp.uint 16 because that's what the original value was there and let's go ahead and run it that seems like it worked let's

47:06 go ahead let's check the shape of that so we'll say study minutes does shape awesome 2 by 100 so our first axis 2 will represent the round and our second access will recommend the day so this 100 here right so this is x is zero and axis one we have two dimensions and our array is now of rank two so i did in fact complete an hour on that first day of round two so that's r2 d1

47:38 do you remember how to access that element why don't you go ahead and do that why don't you set round two day one to 60. so pause me and give it a go when you're ready un-pause me ready now remember it's zero base i hope you didn't fall for that i hate trick questions so let's study minutes and we want to get the second round so one and then we want the first day so that's zero and it was 60 that we're going to set that to

48:13 and then let's go ahead and let's let's peep it let's see what we got going on here awesome so this is the first round right the first round goes all the way there and here's the second round there's the 60 that we got in there great we did it and we'll come back up i'm going to get rid of this displaying of it and we will run that one more time get our space back so you did it great

48:36 but this syntax this these all these brackets that's kind of clunky isn't it well numpy introduces a fun shortcut of a comma so if we wanted to get the value from here we could just say study minutes and we could say 1 comma 0 which is the second row and the first column let's see if that works and it does it feels better right and it's kind of cute now what's happening here it's a little subtle it might look like magic especially if you haven't seen this before but

49:08 if you separate values with a comma like we did here just in plain old python check it out a tuple is assumed so really this is just a tuple in here but we don't want to add all of those these prins we don't need them so it looks nicer like this it's easier to read so in this case each of these values represents an index to each of the axes but there's another way that these indices can work and i want to bring this up now because it can be a bit confusing if it catches

49:42 you off guard there's a bunch of stuff that happens within these hard brackets and we haven't even got to slicing yet it's going to sound like i'm making this up but i want to talk to you about a special type of indexing called fancy indexing in order to show this off i'd like to start with an array that is a single dimension and since our example arrays are now both two-dimensional i thought i'd show off a handy tool for creating some random data to explore let's do this let's

50:11 make a new study log but instead of just zeros let's make it contain fake but reasonable data now this random trick is a great way to create data to play with so here we go so you can actually create a random number generator and seed it in a way that will always produce the same results that way we can have the same random data you and me the seed value so let's do this so

50:43 it's np.random and we're going to create a thing called random state and we'll pass it a seed value and the seed value i'll use let's use 42 you know the answer to life the universe and everything and now let's make a new fake log we'll make a round that was just totally fake and we'll use random integers so we'll say fakelog equals rand.randint because we want an integer

51:16 and we'll make the first parameter it's the low value like how low should it ever go we want it between 30 and then the high of a hundred and eighty that's three hours that's tons of studying and then we'll set the size to be a hundred say size equals a hundred and we'll set the data type or d type to the same thing that we've been using uint 16 the unsigned integer let's go ahead and do that and then let's peep it we'll do fake log there we go this is nice aren't you glad we didn't

51:49 have to type out all of these values aren't you glad we didn't have to study all those minutes our random values here have some that went under the hour so remember you need at least 60 minutes to call the day a success so let's say that i wanted to grab a few of these just to point them out so i can encourage myself to reach the full hour you know ones that are super close to the hour but didn't quite reach the goal i could use some motivation i may want to build a list of

52:16 these values so one thing that i could do is just build a list using standard indexing so let's see we have we want to have fake log and we had to have this value this 44 so this is zero one two three so we have three and then we want the next value four five six seven eight oh fifty that was so close so we'll do fake log and then that's eight right so we'll we should have a list of 44 and 50. there we go those are so

52:52 close to making that hour but this indexing it's pretty basic right there's nothing fancy about it it's just pulling some values out well lift your finger like you would if you were drinking tea as you type out this next one because things are about to get fancy what you can do is type fake log and in here we're going to use hard brackets let's say 3 8 and take a look at what we got back

53:23 there is our 44 and our 50. it's the same type of the values that we just selected pretty fancy right so again using a list as a parameter here is saying return me a new array with the values from index three and eight now check this out it gets fancier the shape of the resulting array can be defined by the shape of the index array so this is just a two element array right let's build an index array in the shape that we want so we'll make a

54:00 2x2 matrix so let's do that so we'll say the index could be named anything we'll declare an array of lists of lists so here we go mp array let's say 3 8 like we had before right so we had those two values and let's just go ahead and grab the first two values for the second row so we'll have zero and one and then we can use this array for our fancy index so we say fake log index

54:27 and we'll see back we got our 44 and our 50 and we'll get 132 and 122 which i'm pretty sure the first two zero and one so we got 44 50 and 132 222 and we pulled it out in a special order and it's you'll notice that the shape of the array is the same as the index array that we wanted now that we already have our study group log in the right rank you know we already have two

54:51 dimensions let's just go ahead and append this fake log to the study group array we'll just redefine the study log because remember these array sizes are always immutable so we can't just add new elements to them we need to create a new one so there's a method right off the numpy module called append so we're going to say study minutes because we're going to override that again equals np dot append and what it does is it takes an array our study minutes array

55:23 and it takes what you want to append so i guess we want to append our fake log and then you tell it what axes to append and we want that on axis zero i've left an intentional bug here for you to see let's go ahead let's run this oh yikes look at this mess all the input arrays must have the same number of dimensions now this is a common stack overflow question so i figured i'd save you some time in the likelihood that you might run into the problem like this

55:54 so the solution here is just to make sure that the dimensions line up so we actually need two dimensions right our fake log currently is just one dimension so one hack is you could just make this a list of lists there we go and if we take a look at our right now we'll see that it has the shape of three arrays awesome so looking at this i see that this one here this is round two

56:32 day two or r2d2 everyone's favorite malfunctioning droid we absolutely have to set that that is one of the most favorite days of these rounds so let's set that one so that would be study minutes one comma one equals 360 right round two day two equals 360. now note here we aren't using a fancy index we're using the comma or tuple shortcut it does get confusing so you really need to pay

57:05 attention to what's going on between these outer brackets right you need to you need to see if it's a tuple or it's a list in fact you can even do multi-dimensional fancy indexing by specifying fancy indexes for each dimension now it's a bit out of the scope for this course so make sure to check the teacher's notes for more on that and now looking at our study log this is about right let's go ahead let's let's run this one more time i'm gonna go ahead i'm gonna go into

57:33 command mode i'm gonna press d d to delete that and let's show our study minutes one more time this looks just about right to me this first round here i let things slip right i got to hear i did that dang netflix binge of stranger things and then i worked a bit too hard on the second round right i did 360 minutes on this day and i burned myself out but i kept on trucking and the third time's a charm it feels pretty realistic to me this

58:06 is probably what a lot of people's rounds look like you have to just keep trying and eventually you'll get it no matter how many times i learn that lesson i need to keep reminding myself stick with it and you'll get it now i don't know about you but some of these minutes on days where i almost made it like where they were almost an hour but not quite like we saw they would really help me keep going during the times where i was struggling to stick with it

58:29 wouldn't it be cool if we could just somehow pick out the values just under 60 minutes to motivate ourselves but not have to pick them out by hand visually like we did well you can and let's do that right after this quick break ooh and also i'm gonna write out some notes on our array creation and appending indexing skills so let's come up here to where we started doing this let's go right here we're gonna go ahead and i'm gonna get into command mode go one

59:01 above change this over here to markdown and i want to talk about array creation then let's also talk about indexing over here so in the creation let's talk about random state and we'll talk about how to append rows and then indexing wise let's talk about the shortcut the tuple one right we'll talk about the tuple shortcut and i also want to

59:32 talk about fancy indexing wow that was a lot that we covered good job i'm going to swing back after a quick break and flesh this out for better notes and then i'll share them with you why don't you do the same and i'll see you in a bit all right before we get started here i thought i'd share my notes as a quick refresher we talked about creation and we saw a new way to build a random grouping of numbers and we used random state to let us seed the randomness

59:58 in a way that was repeatable i have the same random values as you do that is super handy and we also learned that you can append a row in a couple of ways there's even more that we haven't seen here you can append use the np append method you need to make sure that it's the same shape remember we did that little hack where we wrapped it in a list and you can create and reassign a new array by including existing arrays as part of the iterable right so you

60:22 can just throw the new array in there and and reassign it because you can't change the size and we looked at indexing and there's that nice indexing shortcut for the multi-dimensional arrays remember we could use the comma so you can say like three comma four and that's really row three column four and instead of having to use the hard brackets you can use the commas and it creates a tuple automatically and you can also index using a list or another np array and the

60:46 values will be pulled out at that specific index and that's known as fancy indexing the resulting array comes back and it's the same shape as what you asked for but it's very important to remember to look for lists or arrays versus just using a tuple with the comma all right so now where were we oh right we wanted to look at our study log and find hours that were just about an hour but not quite so let's get back down into where we did all that work so so here's

61:16 the study minutes i'm going to get rid of this last this last one here to delete a cell escape and then d d here we go so we have our study minutes array is all written out and remember we were using this fake log so let's start with that fake log because that definitely has some values that we know that are under 60. and remember that's what we're looking for because they don't count towards the challenge the concept being there that is if we saw those ones that almost

61:41 made it maybe they'd provide a little inspiration for us to stick with it for that next day so the in the array object is pretty powerful just about every comparison operator has been overwritten so let's take that fake log object that we're using because it's one dimensional so it's a one-dimensional array and it's filled with a hundred random values so we'll do fake log and check this out i am looking for values that are less than 60 because you know there's 60

62:14 minutes in an hour so i can just write that so fake log less than 60 and what will happen is is it's not defined this might happen to you sometimes so this is good i'm glad this happened so what we can do is we can go ahead and run kernel and say restart and run all and that popped up our help because we left the help up there so i'm going to go ahead and close this and so what happened is we've got this fake log and what will happen is you remember that we

62:46 have these values so the first one that's there is this this fourth so the the fourth value so if we go false false false true and then it looks like again at the eighth there so there's some more false well it's true so what's happening is it's comparing every single one of these values and it's showing us true where it is every value is represented and any place that we see a true it is means that it is true that it's less than 60.

63:14 and that probably doesn't seem all that handy well that is until you find out that you can do fancy indexing with a boolean array the way that it works is that as long as the boolean array lines up with your other array any value where true exists will be kept so here check this out so this is what we want right we want to say anything from the fake log and we will use that boolean array as a fancy index and there we go we pulled it

63:47 all out every value that was true that's exactly what we're looking for right these are all not quite 60. pretty cool right we did that filtering all without a loop you could totally accomplish this same thing by saying something like a list comprehension or or even something similar like this this really simple loop so say results equals this let's iterate through each of the values so for value and fake log if here we go if the value is less than 60 then we're going to say results.append

64:22 value and then just to get back exactly the same thing we'll just use it we'll say mp array results right so there's a loop that we had to write and obviously we got back the same thing but using a boolean array index is orders of magnitudes faster than this for loop and look at the code difference too now something you might be wondering is what happens with multi-dimensional arrays like our study minutes array well the good news is it just works so if we say study minutes

64:55 less than 60 you'll see back that we get an array a boolean array that is the exact same shape as our array so that's 3 by 100 and of course we can use that array as an index so let's do that as well so we can say study minutes where the study minutes is less than 60. boom now notice that we're returned a one dimensional array

65:27 not our original three dimensional array it's all of the values that match now we could rewrite this as a nested for loop of the same type that we did before right like we could loop through each round and then loop through each day and add to our results but we don't need to do that because this is all done for us without a loop what's kind of gross is that's a bunch of zeros right if we're looking to motivate ourselves and we really don't want to see these zeros

65:55 what we really want to see is anything that's less than 60 minutes and greater than zero that get minutes from days where we worked a little bit at least so we want to make two boolean index arrays like we want to make this this study minutes array this this one we want to make that array the study minutes where it's less than 60 and we also want to have another one where the index array is study

66:22 minutes greater than zero and then we actually want to have the results where it's a combination of those anded together you can actually compare arrays together element by element which is what we want to do so i'm going to come down here let's just manually we'll go ahead and we'll manually create an array a boolean array of false true true and to compare we use the bitwise operator for and the amber sand now this is not the and keyword it's an amber sand now common mistake is to

66:58 forget and use the and keyword and we'll explore what happens in here in a bit about that and then i'll create another boolean array that we can compare to so mp array and we'll put in true false true so what happens is we get a brand new array with each element added together so remember when you're checking boolean logic both sides need to be true to be considered true so looking here we have false and true and that's false and then we have true and false and that of course

67:32 is false as well because they're not both true and then we have true and true definitely true so if we go ahead and we run this we'll see that we get back a single array with the values anded together false false true just like we saw so we could use this result as a boolean index array right do you see how we can just build the boolean index array together values that we want to chain together with all of our other conditions and a series of ands and ors

68:03 before we use it i do want to show you what happens if you forget to use the bitwise and as the resulting error is a little confusing at first so depending on how many times you've joined together logical expressions your muscle memory might actually accidentally type the and keyword here so let's do that let's put this and keyword here yuck value error and it's saying the truth value of an array with one or more elements is ambiguous

68:29 so what it's trying to do is it's trying to figure out a truthiness of this and that's what and does it creates a truthiness and if it's assuming that we want to have a scalar value which is not what we want we want to compare element by element so if you did want to get a scalar value if you want to see that everything was true you would use a dot all and that returns a boolean or any if there's any true in there at all

68:53 all that to say just use bitwise operations so just go ahead use a bitwise operation i just thought i'd preemptively warn you about this as it happens a lot more in the teacher's notes so let's build up our index so we want to have study minutes where the study minutes are less than 60 and study minutes are greater than zero right that's what we're looking for but we want to take caution and

69:27 make sure that we're careful about the order of operations this and here is stronger than the less than so what we're going to get is we're going to get 60 and minutes and again we're going to run into the truthy problem that we saw before so we don't want that so let's put parens and or in place to just to make sure that we got the order of operations correct and voila there we have it a brand new array containing entries that represent

70:00 values from our study minutes array that are less than 60 and greater than zero that's pretty cool right and you can see you can pretty much read that more or less right you'll get used to remembering to use the parens and ambersand but i guarantee you'll forget sometimes now one thing we really should consider is this even though we did those minutes there's these these are minutes here that we spent some time they don't actually count for completing the

70:27 challenge the challenge is to do at least an hour a day so in reality we really should set all of these to zero if deleting these minutes doesn't motivate me i don't know what will especially those 58 minutes now even though this index statement this study minutes study minutes less than 60 even though that creates a brand new array if you assign to it you can do an update and

71:04 if we look now we look at our our third row there we'll see that we add some zeros in where they were not before yikes look at all those all that time didn't count because i didn't reach that hour now of course that time did actually count i was learning but it didn't count towards the challenge i'll tell you what this hundred days of code challenge totally motivates me so losing that time definitely will keep me focused in the future it reminds me that i just need to stick with it

71:38 i want to complete this challenge speaking of challenges i'd like to again challenge you to capture your thoughts on boolean array indexing in your notebook remember to think through the possible gachos that we walk through like accidentally using the and keyword or forgetting to use parentheses if you've ever done sql programming before that might have felt familiar capture those thoughts a bit also now is a good time to take a moment and review your notebook is everything in there clear if not please hit up the community and ask your questions if you're

72:10 looking to solidify your knowledge i highly recommend attempting to answer someone else's questions i can't recommend it enough by taking the time to explain a concept you will uncover new knowledge give it a shot it won't disappoint so far what we've been doing is returning a new array but you can actually return a view of the data that you can manipulate let's take a look at data views and some more powerful slicing features next you know how when you don't use a skill for a

72:38 while you need to practice it a bit before you can get right back to doing it flawlessly like no matter how good you ever were at it it's where that saying use it or lose it comes from well for me in addition to juggling that skill i need to dust off is slicing an object you've probably used slices before on lists or tuples but if you haven't done it for a while you could be a little

72:59 klutzy this is where practice comes in and i want to encourage you to practice and test things out let's practice a bit of slicing with lists first just to warm up and then let's practice with some multi-dimensional arrays it's like starting with these practice juggling balls instead of say chainsaws jupiter notebooks are excellent for this sort of practice but oh actually real quick before we get into our slice practicing let's make use of another great feature of notebooks

73:28 notes so here are mine on boolean array indexing so you can create a boolean array by using a comparison operator on an array and you can use boolean arrays for fancy indexing like we saw kind of like a where clause there from sql and boolean arrays can be compared using bitwise operators that's and and then the pipe sign there is or and remember don't use the and keyword and also remember to use the order of operations otherwise

73:55 you get that really weird value error that we saw and even though boolean indexing returns a brand new array like a copy you can update an existing array by using a boolean index so let's go down to the bottom here the very last row and if you want to clean some of these up you can i'm going to get rid of some of these just ddd in command mode there all right so let's make a new list my go-to list is this fruit we'll go ahead we get apple banana cherry and durian

74:34 all right now let's warm up those slicing skills now for some reason i can never remember if slices are inclusive or exclusive so when i'm not sure one thing i like to do is just try you're not going to break anything right all right so let's get a slice of this list i want to get a portion of this list like just the second and third value so let's see i know that things are zero based so

75:02 i know that i want to get the second one i'm gonna start at one and then i want a colon signifying up two and now is it inclusive or exclusive i don't know i'll try inclusive so let's see one to two no it's exclusive oh missed it by that much so if we come back and we say one two three we'll see that we get banana and cherry so it's like up to but not including that's what you can read

75:30 with this is like one up two but not including three phew all right and then again if you leave either side blank so if we say fruit and we go up to three we'll get everything up to the third one which again not the third one the fourth one this is zero based and then if you do at the start you can say fruit from three onwards so we'll start at the third and go to the end and there's durian

75:59 mmm the cheese of fruit so just a plain colon then if you just use a colon it will give you a copy of the array it's basically a copyright from start to end in fact this is typically used as a way of copying standard python lists so if i store that in a variable so we'll say copied equals fruit and then the colon so give me everything and then we go ahead and what if we modify that copy if we say copied

76:30 three that lasts that durian we're gonna set that to cheese if we set that to cheese and then we take a look at let's say slicing a list returns a copy and i'm going to spell slicing correctly slicing a list returns a copy so if we look here if we look at fruit and then copied we're just going to make a new tuple of those two so we can look at the values next to each other

77:01 we'll see that fruit was not changed when we changed the copy of that they're actually two different places in memory okay and there is a third part to this slice the step now by default this is one it moves one element at a time but i can add a second colon representing a step let's say that i wanted to get every other one so we'll say fruit there we go apple cherry and we skipped banana and durian

77:33 so instead of stepping through each element one by one we went by two and you can also use negative to walk backwards right so if we say fruit negative one we'll see that it runs backwards and there we go i think i'm refreshed i think i'm ready to start juggling those chainsaws my de facto test list go to is this one of fruit when it comes to creating a numpy array to explore the most common way is to use a function named a

78:05 range which is very similar to python's range function but instead it returns an nd array so if i say np.a range and i pass it in the ending value there so it goes up 2 and not including 20 you'll see that we get all of the values up to and not including 20. so let's go ahead and create a new practice array here and we will make it mpa range and we'll go up to our magic number 42

78:39 and you can actually change the shape property on an array so we can say practice dot shape and we're gonna assign it let's go seven rows six columns so let's do that and then let's take a look at what practice looks like awesome so let's go ahead and get this number 13 here lucky 13. so this is a two-dimensional array or matrix and really it's just an array of arrays so we first need to get this row here so this is zero one two so we have practice

79:19 two okay let's make sure we got it yep and that's just an array so we need to get the zero one we need to get the the one there there we go there's 13 and that is entirely too many hard brackets so let's express it with just a comma so 2 1. awesome so as you can expect the nd array is pythonic so it too allows for slicing so if we wanted to start at the third row here

79:47 and go to the fifth we could just do this we could say practice two to five and there we go we got just those rows awesome and if we wanted to just get this column here we could just put comma three awesome and we can also slice this column dimension so let's get the fourth column until the end so we'll say three until the end and there we go now we have 15 16 17 and then if we wanted

80:23 to step every other column we could say three colon colon two and there we just have those two look at that we stepped right over that column right so we skipped right over this column we limited it then we sliced it and we got these three and then we get skipped over that so we got just this 15 to 17 21 23 29 pretty great right now one thing that'll bite you if you don't know about it is that slices in numpy don't return a copy they return a view of our data now

80:56 this is different than we saw in the standard python list so let's explore this real quick i'm going to write not copied and we're just going to get everything we're going to take our practiced array and i'm going to actually i'm going to make a comment here for us later as we look over this any slicing of indie array returns a view and not a copy okay so i'm going to go ahead and i'm going to set

81:25 not copied i'll set 0 0 the first the first one there 90210 and we will return practice comma not copy just so we can see them next to each other and we'll see that both of them changed and that is because this is a view and not a copy right it's exactly the same it changed the original array practice and that's

81:56 because not copied is actually what is known as a data view and as you can tell it's kind of hard to know just by looking at the representation of the array but they're views and not brand new arrays so one way that you can check to see if you have a view is to check the base property so if we look at this we can say practice dot base is none and that's true but if we look at not copied dot base is none we'll see that that's false

82:30 because it is copied and then also that base is set if you say not copied dot base is practice we'll see that that's true so you can always see where it was copied from there's also a property called flags on arrays and it's a dictionary and one of the keys is called own data so you can check that as well if you wanted to you could say practice dot flags does this own the data and that one should be true and not copied does not own the data it is a view so data views are

83:08 important to understand and be aware of as you don't want to accidentally modify a structure that you didn't intend to data views are part of the trick of how quick and seamlessly you can rearrange data in numpy so you will see them used in the wild quite a bit now the one major and not initially intuitive place where data views get created is in slicing like we just saw so i'd like to make sure that you recall that when you slice an array of any shape

83:36 that you are creating a view and not a new array or copy as happens with standard python lists a view references the same values in memory while a copy would be a brand new space using a slice or view is handy as you can pass only part of the array around for processing but not require the entire array by not creating a new array we are not only saving memory but we're also allowing a reshaping of the array we're allowing portions or slices of the array to be modified

84:11 let's take a look at some more data view creating functions and actually i'm going to take some notes on slicing and slicing multiple dimensional arrays specifically i'm also going to make sure to document that little data view gotcha let's review that right after this quick break we were able to change the shape of our array by setting the shape property directly now this is handy when you want to permanently change the arrangement of your data but that's not always

84:36 going to be the case you'll find as you work more and more with data sets that you're going to want to temporarily bend and mold a view of your data to work with but leave the original one intact this is where those data views like the ones that we got from slicing come in handy there are a ton of ways to manipulate your data let's take a look at some of the more popular techniques and i'll show you how and where to learn more oh first though let's compare our

85:03 notes on slicing so slicing works a lot like normal list slicing it's very pythonic and you can use commas to separate each dimension slice right so you can slice the dimension and it always returns a data view remember that not a copy that's very different than that and it's but it's important to know and you can always access the base object using in the array.base awesome so remember we changed the shape earlier we changed the shape where'd we do that we just

85:32 changed it right here specifically once and we changed it permanently we changed the original practice array that way so you can actually create a view instead by using the method reshape let's remind ourselves what a practice array looks like it's a 7 by 6 right so all the way up to 42 so let's assume that we wanted to have three rows and that would be 14 columns right so we will do that we'll say we'll say practice view

86:02 equals practice dot reshape 3 comma fourteen and just to make sure we go get practice and then we'll get practice view so we're just we're just gonna pop these out here to take a look i figure this is a handy way to do it all in one line and then we'll say practice view dot base is practice okay so we're gonna make a view off of that practice arrays so here we go we now have a three dimensional array instead of a seven by six and you'll see

86:35 that at the end here we've got true so it is the base so the view isn't taking up any more memory it's just pointing to the original data which allows you to save space and it gets things in the proper shape as you need without wasting space reshape also has a great feature it'll infer what you want if you pass it a negative one to any dimension so for instance let's say practice dot reshape and we're going to give that the first one i don't know all i know is

87:06 i want two columns right so you'll see that that inferred 21 if we go here and we say dot shape see what happened there is we've got 21 by 2. awesome right now a very common reshaping that you'll want to do is all of the elements in a single dimension like you'll have you'll have something shaped up but you just want a single dimension which you could reshape with just a negative one but there's a better way so we can say practice dot ravel

87:38 and you'll see what happens here is we get a single dimension and it kind of unravels all of those dimensions now this is a view and not a copy if you do want a copy you can use the method flatten flatten creates a copy how do you remember that though well the answer is you don't like most things in this programming world you just need to remember that you need to lean on documentation numpy's official documentation is pretty good so let's take a quick peek

88:09 i have this page bookmarked and if it were an actual book the page would be worn it would have tons of highlights and circled entries and lots and lots of coffee stains numpy's reference guide is very well indexed on the oracle of your choice so i'm going to use google and we'll say array manipulation and we'll do numpy and this first hit here is what we want so let's do that so here's the page usually whatever you

88:40 may be trying to do manipulation-wise can be found here so let's scroll down a little bit changing the array shape looky here here's reshape here's ravel and here's flatten so let's click in to ravel here and it returns a contiguous flattened array awesome contiguous meaning one element after the other no space in between and then flattened meaning the dimensions are removed and a one dimensional array containing the elements of the

89:13 input is returned a copy is made only if needed so there we go it's a data view we could just look up this documentation and know that it's a data view these docs do end up working a bit like a wikipedia hole where one topic leads to another one and before you know it you've read half the internet so just a word of warning this see also section is a bit of a learning rabbit hole so i want to point out that i really like the notes and examples that these pages provide

89:42 seeing the example show the function in action and often times there's extra information talked away like for instance here it says this is equivalence to reshape negative one which we just talked about right remember how reshape takes the negative one if we wanted to ravel we could do that so so here you go here's np ravel two arrays there it is and it's saying that it's equivalent there's reshape negative one and there's ravel and it's doing the same thing

90:08 there's some extra talk in the doc here and in several functions about order this deals with the way that we talk about indices and how they're stored in memory now this is out of the scope of this course but i do want you to know that all of the functions that we are using use c as the ordering default and actually in most cases you'll see that that makes sense if you'd like to learn more about index order check the teacher's notes okay let's go into our hole here and let's

90:35 take a look at flatten so let's assume that we found this page first and here in the description we see very clearly that this returns a copy of the array collapsed into one dimension and if this wasn't what we wanted we could also come down here and we could see that ravel would probably work and there's another quick way to get at this information if you don't feel like leaving the comfort of your notebook so let's go back to the notebook and i i totally get not wanting

91:06 to leave the notebook there is no telling what's going to distract you if you open up that browser am i right so the numpy team did something super clever and built a search engine for doc strings so imagine this is a few days in the future and you're in your notebook and you want to make sure that you get that one function you know that one right hmm what's the name of that one again the one that makes the array flat but it's a view and it's not a copy what was that called

91:30 hmm well i'm going to search for it i'm going to look for it so i'm going to np dot look for i'm going to look for flat because i remembered it had something to do with flattening so here's the stuff oh here it is a contiguous flat an array that was at ravel and let's just make sure that that's right so i can come up here and i can say mp.ravel and do a question mark and is that that what i was talking about yes contiguous

91:59 flattened array so check this out it's the actual doc string so it's got the parameters there's the returns there's your c also there's the notes that we talked about and here's the examples pretty rad right this look for function is super handy for not getting interrupted and or going down a documentation internet hole so anyways let's get back to that bookmarked page and explore what else is on here so i'm going to come back up here and i'm gonna go back

92:29 and back again get back to our list awesome so transpose like operations transposing lets you flip the order of the array around it switches the rows with the columns so if you had four row by three columns transposing would give you three rows by four columns the same data it's just flipped around so you'll see this referred to with the property of capital t here so let's go ahead let's get in there because this is a little strange and you'll see them here's

92:54 a great example so we've made a two dimensional array we've got one two three four as rows and if you do x dot t and again that is a property on there now it's it's flipped right so now we have one and three and two and four so we have one and three as the rows and two and four as the columns it just transposes it this is handy for quite a few equations that require you to invert a matrix

93:18 i just wanted you to understand what the strangely named property t is doing you'll see this thrown around quite a bit in examples and blog posts so let's go back and scooch down this document a little bit here changing the number of dimensions changing the kind of array joining arrays this is important here much like we can split and join on strings this is a similar idea it breaks apart and puts together multi-dimensional arrays now the thing that i want to point out here

93:46 is that this h prefix that stands for horizontal v is for vertical and d is for depth in a three-dimensional space so again these methods are all handy for when you want to stitch together the proper matrix for a particular equation there are a plethora of options for manipulating your arrays to match just about whatever shape you might need there are tons of well-documented recipes for adding rows and columns i'm glad that you've got access to that array manipulation page in the

94:17 documentation i'm sure it will serve you well it has me why don't we both go and add some notes to our notebook make sure to include a link to that page also don't forget to take note of that super handy method that we talked about to search the documentation look for i'm going to review that manipulation page and just kind of jot down anything that i want to remember now i know these manipulation methods have been a little abstract and it's kind of challenging to imagine why you

94:42 might need to use them this is one of those cases where it's handy to know what you're capable of doing when it comes time to use your skills and i don't know about you but i always disliked that part of math class i was always like but why let's see if we can't answer that question let's take a break and swing back and start exploring some of the more powerful math features of this library you've done an excellent job learning all about numpy arrays you can create inspect and modify

95:13 them you can manipulate them into new shapes and you can filter out the values you don't want and now i'd like to take some time to show off some common use cases for these arrays that we've been getting to know but before we dive in here i'd like to take a second to discuss a phenomenon known as imposter syndrome imposter syndrome happens when you doubt your skills and you feel like you really aren't a pro you feel like a fraud you feel like everyone else knows more than you

95:39 it's an unfortunate and quite common feeling and i want you to know that you aren't alone in experiencing it and i especially want you to know that you aren't actually a fraud and that you can do this because of the numerous use cases of numpy arrays you're bound to see lots of math equations and formulas that you don't yet understand you might have learned once and have forgotten what happens is you think man i only know this much stuff look how much everyone else knows

96:04 but here's the thing very few people know it all they all know their own little bit and you can and will learn the extra little bits when you actually need them this is important to remember that feeling is bound to happen to you and i just want you to be ready for it approach it like hey i'm not sure how to do that yet because you will learn it and look at you you're doing great already i want you to approach things with the growth mindset check the teachers notes for

96:29 more on that we're going to be doing a different type of programming than we've been doing up until now on our python journey together we're going to be doing what is known as array programming instead of our typical way of looping through a collection of data and pulling out values one by one to perform operations what we do in array programming is to perform the operation on the entire set of values all at once in one fell swoop not only is it faster it's also expressed

96:54 much more concisely in code array programming code often ends up looking a lot like a math equation we've talked about how an array is referred to as a vector in a two-dimensional array as a matrix well the reason for that is because we use these arrays to represent their mathematical equivalent it's probably a little too abstract let me show you what i mean by that statement oh i got an idea let's do some linear algebra why the long face that doesn't sound fun did

97:23 you forget how to do it too don't worry all we have to do is set up the equation properly using the correct layout and numpy is going to do all of the work for us i had a moment recently where i had to take back one of those famous quips that we all make at one point in our lives regarding stuff we're learning you know the one when am i ever gonna need this oh probably not very surprising to you by now but this example involves tacos

97:46 there's a new taco food cart that just opened by our office and i like to share my love of tacos with my coworkers so i often offer to do pickups for the office now if you've ever been in charge of a taco run you know that one of the main problems is that you're never quite sure the price of the items so i'm usually just like just pay me letter i'll put on my credit card and sometimes determining that price from the total is easy like in the case where you have two

98:09 tacos and the total is three dollars you can do that kind of math in your head right so you might not even know how you did it but you know that a single taco costs 1.50 cents that's pretty simple if that was the only item on the order but that's never the case right so i know one of the larger orders i bought was four tacos one burrito two horchatas and two mexican cokes and the total

98:30 was twenty dollars and fifty cents nothing is better than a mexi coke and a bottle real sugar with that information though i have no idea how to figure out the price breakdown it's definitely not as easy as that two tacos equation that we did in our heads and this is because there are so many other variables now but i seem to remember from math that if you have enough equations you should be able to solve them so let's see do i have more data of course i do i went once and i got

98:57 a burrito and a mexi coke and that was ten bucks oh and another office pickup i did six tacos one horchata and two mexicos that was 14.25 cents now one thing i remember from math is we're going to need to make sure that everything is lined up that means i need to make sure that i enter a zero for all the items i didn't purchase and we get some nice looking equations here now if that doesn't

99:19 look like a math equation to you what if we change those variables to their typical looking form don't let those freak you out though remember they're just representing tacos and burritos and whatnot so really this left side here kind of looks like rows and columns almost doesn't it in fact let's make the type of food the heading here and what we have left here is the number of items or the coefficient in mathematics to denote a matrix you will see hard brackets like this

99:44 and for our totals we can consider this as a single dimension array or as it's called a vector a row base vector to be precise and with our system of equations as a matrix and our totals as a vector we should be able to solve for it there are definitely rules and ways to go about solving that system with linear equations but what do you say we let numpy do the work for us in the teacher notes attached to this video i've added the equations to create our matrix so i'm

100:11 going to copy and paste it here in the cell so here is our orders array and that's our matrix right that's what it looks like it's an array with a rank of two it's got two dimensions and each row here represents an order right and this is the number of tacos this this first first column here is tacos right and then the next one is next one being burritos and then horchata and coke right and now we need to get our constant prices so that's also in the

100:42 teacher's notes let me just paste that here so these are the totals of what came across scroll this up a little bit there we go so we got our three dollars 2050 for the second order 10 and 14 25. so really what we've done here is to build the math equation right well now for the awesome part we don't actually need to know how to solve this we just need to know that it's a system of linear equations that we're trying to solve for and we also need to know

101:14 that there is a module in the numpy library for linear algebra it's shortened to lynn alge here is the beautiful method solve and we pass it our coefficient matrix which was our orders and we also pass it our totals so we say totals like so and then let's go ahead and take a look at what prices is look at that dollar fifty tacos we knew that eight buck burritos a dollar twenty-five

101:44 horchatas and a mexican coke for two bucks please please no tariffs that coke is more expensive than a taco already but well worth it wait a second if we have this solution i think we should be able to verify it right i mean if we just plugged in these prices to the equations it should produce a total right shouldn't it so let's see naturally in python i guess we would just loop through the matrix and then loop over the prices and multiply them together

102:16 and then we'd add them together right and that should produce the price now we could definitely do that but let's remember that one of the benefits of array programming is that we don't need to rely on loops also if there's a mathematical way to do something most likely there's a way to do it in numpy now what we're talking about here multiplying matrices with vectors and then summing them together is actually a common math practice and it's

102:39 referred to as the inner product and it's usually represented with a dot so you would say like a dot b that's exactly what we would have done in a loop but expressed in mathematical terms the notation right so in python though that dot that i just created that doesn't have any meeting so instead we can use the at sign like so so if we say orders orders at prices let's see what happens so check that out that is what our totals were look at that it

103:13 adds up so it took these and ran them through the equations and ended up with the same totals so we know that it works and so really this is shorthand for orders dot prices see it's the same thing pretty cool how we can use these shortcuts to build and solve equations right it's super powerful and i'm glad that you have all those array manipulation powers in your bag of tricks as i know you're aware linear algebra has many more applications than just taco price

103:44 calculations it's great for times like we just saw when you're trying to solve for missing variables in a bunch of equations and remember this is just one formula there are so many more and many of those formulas that are available for you to use will most likely not be familiar remember that's okay no one knows them all you'll learn them as you need them don't let the options overwhelm you let them make you feel empowered you don't need to know how to solve them yourself and that

104:11 should feel great that linalg.solve function is a bit of an abstraction it really is doing all that work that you would have had to do by hand like you might have done in math class it's very similar to how we could have written that dot loop there's actually a function that does all the heavy lifting for us what do you say we take a quick look at some more common vector-based operations that you'll encounter as you progress let me show you off numpy's universal functions or

104:37 u-funcs first though let's take a quick break and why don't you jot down some thoughts and notes about what we just accomplished all without using loops oh yeah quick reminder make sure to check out the teacher's notes on this video i've dropped a lot of information about where to learn more about linear algebra if that got you reinvigorated and like i said it's no big deal if it didn't there are many more use cases for numpy see you soon and we'll compare

105:01 notes when we perform operations on our data all at once without using a loop the operation is said to be vectorized it's not only faster but we usually end up writing fewer lines of code out of the box there are quite a few numpy functions that are available for you to use that are already vectorized these are referred to as universal functions or u-funcs when there's one of these universal functions available for what you're trying to accomplish you want to ensure that

105:27 you make use of it before you start writing a loop look first to the ufuncs let's take a look at the more popular examples of these universal functions and then i'll show you where to learn more here are my notes from the linear algebra exercise that we just did so there's a module for linear algebra and it's len elge there's a link to the documentation if you want it and you can also solve for a system of equations using the solve function which was amazing right we just made that

105:54 two-dimensional matrix and we had a constant row vector and we were able to solve for each variable and then we were able to double check using the inner product or dot again there's a link to the documentation and again in python 3 and up you can use the at sign there to produce a dot product of two arrays awesome some of that abstraction that was going on in the lin alg solve function was using some vector math right and this is super common in just about every direction you had with

106:24 numpy you'll want to perform some operations on two vectors together let's take a look at what that looks like real quick so how about we make a couple of example arrays let's go down here and let's make some example arrays so for our purposes we'll make one dimensional raise and let's unpack some into a and b and we'll just use a split method so we'll say np dot split let's see let's make a array of 1 through 10. so we'll say np.a range and remember it's

107:01 exclusive but we'll start with 1 and we'll go to 11 up 2 and not including 11. it's exclusive and the last parameter of split is how many you want so we want to take one through 10 and split it into two and then let's just double check we got what we wanted we'll print those out awesome so we have one through five and six through 10. so what happens when we add these together now i know in regular python world this would make a new list with all of the

107:30 values right let's explore what happens when we do this with nd arrays so we'll say a plus b that's pretty cool right it does vector math it adds each element as they line up right so we have six plus one is seven and we have seven plus two is nine and eight plus three is 11 and so on so the plus operator has been overloaded for these nd arrays and i bet then the other ones must be

107:59 two right so what happens if we do a minus b we get an array of negative fives right one minus six is negative five two minus seven is negative five and then of course the order matters just like in math right so if we do b minus a now we should get all fives awesome so then does that mean that we can do a times b it does awesome and so then what do you think happens

108:25 when we add a scalar to that array so what happens if i do a plus two interesting look at that it took the right side this 2 and up it applied it to every value so 1 plus 2 2 plus 2 3 plus 2 it's almost as if there was a right side that was the same size something like this so there's this there's this method that you can do you can say np dot repeat so

108:54 we want to have a that's five we might have five an array of twos that's five long so that's would look like that and so basically the same thing is happening if we did a plus that right we get the same thing so it stretched that two that's pretty neat right so this ability to just stretch the scaler value across all of the items is called broadcasting the value 2 is broadcasted across the array named a broadcasting is handy because we don't

109:26 actually need to create this array right we don't need to do that ourselves the equation automatically assumed what we meant now you'll see broadcasting relied upon quite a bit these operators have all been overloaded and are actually using universal functions or u-funcs and remember u funcs are vectorized see how we didn't have to loop through the array ourselves it did all that looping behind the scenes for us let's pop over to some documentation for these you funks one of the great things about this weird naming is i can just search for you funks

110:03 and i'm gonna find the documentation there it is the first hit my wife also says that to me every time i come back from the gym she says ew you funks well that joke really stinks and i apologize in advance for making you think about that bad joke every time you hear the term ufungs this is a helpful page as it details the rules of broadcasting as well as unir universal functions and broadcasting again that array stretching that we just saw which is super

110:31 important in vectorized operations again are no looping functions so in the table of contents on this page which is not showing because it's so big i'm going to shrink this in one there we go so here's this table of contents over here we're going to take a look at these available ufuncs cool i'm going to blow this up one more time now that we're here and so here's the available ufunks and what we can look about here's the ad we just we just did that let's go ahead and

110:59 click into it so you'll see that if you use the style of calling the function that we have extra arguments they're optional right so they're where equals true for example you can choose which specific elements to operate on okay and you can choose to cast it to something else as well if that's what you're looking for but these first two arguments this x1 and x2 that's the left and the right that we were talking about so you'll notice here in the description that it says that

111:27 they must be broadcastable which is defined in those broadcasting rules that we skipped over just a bit ago in the ufunk's documentation let's scroll down here because there's some great examples so you'll see that you can add just fine you can add scalar values together so if you have a scalar plus a scalar it returns what you would think it would and the second one is showing another example of broadcasting which i think we should explore because this is showing a three

111:53 by three and then it's adding by a three array so let's take let's go ahead let's let's copy and paste this so i'm going to copy this over to our our notebook and i don't know about you but sometimes i have a hard time seeing what it is exactly that's happening so i like to say x1 comma x2 and then we can take a look at both of them and i'm going to move this down here

112:16 one of the great things about the notebooks is it lets you keep those chevrons in there those those greater than signs it's not going to bother anything so that's awesome for copying and pasting so there we go so we have our our array here and this other array here and what's going to happen is we are going to add those together i'm going to get rid of this we're going to add those together so let's take a look and see what happens

112:39 so it broadcasted this array over each row so 0 plus zero that's zero one plus one is two two plus two is four and then again it took that to the second one it broadcasted there so zero plus three is three one plus four is five see how it's going there it's pretty cool right and also scalars can be broadcast to multi-dimensional arrays so if we also do np add comma 2

113:09 we can see that the two is added to every single one of the values see how it's broadcasted to each and every value so let's switch back to our documentation so there's some more math operations these are what was being called when we were doing the overloading basically right so there's subtract multiply divide let's get through all these square root that's handy all right trigonometry functions super handy that is if you need them i know that trig can

113:38 trigger some people don't let it the important thing to remember is that you can run these functions against all of the values in your array all at once which is super powerful if you need to use these you'll be very happy so we look at these here's here's hipot for hypotenuse the old a squared plus b squared equals c squared this creates an array of all the c's pretty nice right here's some low level bit twiddling functions again handy if you need it

114:09 if you're dealing with binary data and you need to move some stuff around and then here's some comparison functions and this too is operator overloaded remember when we used the less than sign to see all the minutes that were less than 60 well that was using this less ufunc and then when we wanted to check that that comparison was true and it was greater than zero we used logical and oh look here's that warning about not using the word and or or but instead using the bitwise

114:37 and and or signs and here's another warning that we saw where we needed to make sure that the order of operations was used right so it's again warning about the fact that two and a is evaluated first awesome this is reminding you to do like we just learned remember when we use that less than 60 the 60 is scalar and we just broadcasted that to each and every element for comparison broadcasting is pretty straightforward most of the time it's usually either a scalar or a row like we saw

115:08 however if you end up seeing it happening and scratch your head about what's going on you should bring this page back up right so bring this page back up because up here at the very top sorry for that scrolling that might make you sick this broadcasting here these rules are detailed out and it's super handy if you can't figure out what's going on and it's it's nice to review from time to time i don't want to overload you with these rules i just want you to know where

115:34 to find them defined and that's eu funks for you super handy right you definitely want to lean heavily on them there is optimization that happens at the core numpy level and you can actually even write your own check the teacher's notes for more information so why don't you jot down some notes about you funks and vectorization in general maybe toss in a couple words about broadcasting and i'll do that too and after the break we'll review them and check out some more handy routines

116:04 so here's my notes on you funcs or universal functions they're commonly needed vectorized functions again which allow you to operate element by element instead of using a loop and standard math and comparison operators like plus minus multiply and greater than greater than equal to they've all been overloaded so that they can make use of vectorization and values can be broadcasted or stretched to be applied to the vector right so remember that two got stretched all the way across a scalar or we did it by rows

116:35 awesome so we saw some super powerful ufuncs and let's go take a look at some higher level routines that make use of them for common tasks now all this talk of trigonometry is making me want to go back and take a look at one of those first multi-dimensional arrays that we created that students gpas that was way up here at the top wasn't it let's get back up here you've done a lot in this course all right so here we go here's our student gpas

117:05 let's go ahead let's take a look again one more time at what that is so we'll say students gpas right so the zeroth row of this is me and then we had vlada and then we had quasi awesome one thing that we can do is we can find out the average or mean of this data so the way that you do that is just call a function on it say students gpas dot mean

117:40 oh whoops that returned all of our scores averaged together which 3.805 is not bad for our cohort average however i was hoping to get a mean of each row of these students now the great news is that there is an axis argument that we can pass and it will do what we want the parameter though has been known to trip people up so let's focus a bit on the issue so we have a two-dimensional array our first dimension is students and our second dimension is of gpa by year in school right so

118:17 we want to have the mean of the second dimension right we want we want this dimension this is what we want the gpas is what we want so that would be access one remember that they are zero based so x is zero is the other way so access 1 is this so let's go ahead and do that let's say the students gpas.mean and we'll do access equals 1. and since we've got three results here and we only have three students we know that it did

118:51 the right thing it went across and did the average there so there's 3.69 let's go ahead and say 3.7 and then there's 3.75 and 3.97 and by the way that 3.7 didn't really mean anything now a common mistake is that people think that they want to work with each row so they choose to access zero but really what happens with access zero let's go ahead and do that we'll say x says zero is it ends up going this way right so so it it's averaging access

119:24 this way because it's reducing the values it's summing all these values up but we want to go this way so when you think about the access remember it's what direction you're moving in totally common hiccup just remember to imagine the function happening across a dimension now you might want this sometimes though right this access zero will give you the average of all students by year that's what you want and then if you want to you can do access one and it gives you

119:56 average of all years by student this type of function is known as a reduction operation the function reduces a set of values down to one the concept is that there is a function that takes two values a total value of all operations and the next value in the array-like object it performs the operation returns the total to be used in the next iteration recursively might sound complicated but it's actually what you would do in your head if i asked you to add up all the values

120:24 in this list it's probably easier to just see it in action so let's do it all functions that are you funcs have the ability to do this built into it here let's go back down to the hundred days of code steady minutes list where is this at let's go down to where we have the very last one of them here we go study minutes let's here we go

120:55 all right so i'm going to add one below this remember that our study minutes array is a two-dimensional array the first dimension represents rounds or attempts and the second dimension is the minutes per day and there are a hundred days so let's simplify things first by using a single dimension i'm gonna grab the first round here so we'll say study minutes zero now if i asked you to total these minutes up i bet you just start adding and

121:23 remembering like this you'd say okay so 150 plus 60 that's 210 and now i go 210 plus 80 that's 290 and then i take the total of 290 and i add 60 to get 350 and so on and so on and so on that is reducing in a nutshell if we continue all the way through the array we'll have a total now i said that all you funks have the ability to do this reduction and the way they provide this

121:51 functionality is by exposing some functions off of the ufunc itself that sentence was pretty funky what we were doing was adding all the values up in that case the ufuncle that we'd like to use is add so let's do it so we'll say np dot add dot reduce and then we'll pass in our array and there it is 440. and it did just like we were doing if you want to actually see each

122:24 step there is a function for that available too on each u-func so np-add.accumulate and this will show you each step through so if we do again if we do study minutes zero we'll see that we have 150 210 290 350 and then actually you'll see all of the zeros ads that we had to do and yikes you can see the waste of time that we made this do by adding all the zeros we could have filtered them out more in the teacher's notes now we want to get the sum of all these

122:57 values together and there is of course a routine that's super common and it is called sum so if we just make this mp well let's make a new one let's say that there for us mp.sum and we say study minutes zero we'll see that we get 440 which is exactly what we did when we did the reduce and the reduction works on on multi-dimensions as well so we can just say mp.some study minutes and it

123:28 will get wow 10 000 hours must be a pro i guess what macklemore said or malcolm gladwell i can't remember which one said that reduction functions will almost always define an access parameter so in this case we want to see the sum of all minutes by round so that's access one and there we know that we did it right because there are three results turned back and 440 was what we got we were getting for the first one awesome pretty handy right and as you can imagine

124:02 that mean function that we were just using is probably using this sum function under the covers since to calculate the mean what you do is you add all the values and then divide by the total amount of values but what's nice is that you don't need to remember that formula now even though it is simple it's been abstracted away for you by simply calling the mean function you'll find that there are lots of formulas abstracted away for you in the library in fact let's pop over real

124:33 quick to another popular page in the documentation i'm just gonna google statistics num pi here we go there are tons of functions available for you here since it's statistics a bunch of these are reduction based they reduce all the values down to one and here's one that you'll see everywhere std and while it's actually known to spread itself

125:03 around it's short for standard deviation here let's pop in so it computes the standard deviation along the specified axis it's the measure of the spread of a distribution which is great and if we scroll down here in the notes we can see that this is what has been calculated this is the formula now i kind of remember doing that in math class but the point is here you don't need to know how to calculate it you want to know why to use it as we discussed when we first introduced the grade

125:36 point averages or gpas people struggle with math concepts when they are first introduced to them and i'm under the belief it's the memorization of the formula that most people struggle with typically that's what you're tested on not the actual way to use the function in the real world current learning science says that if you don't use it you will lose it so if these equations feel a bit rusty and you haven't used them recently don't fret your brain

126:01 is just working correctly most of the time you hardly get a chance to see why in your math class you just focused on the how so with that said let's pop up a couple levels here in our bookmarks to routines this page here is a really great overview of how powerful this library is and a great look at some common abstractions so if we look down here here is some discrete fourier transforms here's some financial functions linear algebra

126:39 input and output logic functions polynomials statistics there's a lot in here remember you don't need to know all of these just be aware that what you're trying to do most likely already exists as you can see there are tons of directions that you can head with this library so stand on the shoulders of giants who built things out for you we talked way back when about how all sorts of different libraries accept and return numpy arrays let's take a quick break and take a look at one

127:14 common use case plotting values on a graph well that is right after we jot down some notes why don't you talk a bit about some common routines that you saw and talk a bit about reduction just about every python data library that you come across is going to accept and produce numpy arrays let's take a look at a common use case plotting our data graphically let's go and get matplotlib installed so here are my reflection notes but before we review them

127:43 let's multitask we need to install matplotlib so let's flip over to our terminal and we will stop the server with control c and do i want to shut this down i'm going to click yes to shut it down we go back at the prompt and we're going to type conda install matplotlib and as that starts happening we are just going to go and flip over back to our notebook i'm going to say okay it's still up so it says connecting the kernel that's fine because the server's down

128:14 so let's take a look at this so some common mathematical routines are exposed so the formula could be abstracted away right that was awesome so we saw mean was like that std or standard deviation was like that a note here of reduction functions take a dimension and it will collapse it will reduce across that into a single value and that access parameter is one that's a little bit tricky good thing we made note of that with some examples awesome and it

128:39 works across the dimension so that's the common routines and i did another one another little section here about the universal functions so here we go universal functions expose a function to reduce an array to a single value and there's also a function called accumulate which is nice because you can see things as it accumulates let's see how we're doing with our server oh shoot yes we want that to install i was trying to be a little too faster all right cool here

129:08 we're good so let's go ahead and let's start that notebook back up jupiter notebook and we should be able to just do it over here if we come back here and we say kernel restart and run all here we go back to it if you haven't used matplotlib before it's a wonderful versatile and quite popular graphing library there's more in the teachers notes if you'd like to learn more so i'm going to come up here into my imports and i am going to add matplotlib so we'll say import

129:46 matplotlib dot pi plot and keeping things lazy it's called plt typically as plt awesome so what can we do with that well what do you say we create a graph that shows the student's gpa's matrix so let's get down to where that was at here we go let's get rid of a couple of these d d d dd and i'm going to come here we should probably convey the way that each student performed over the year

130:22 now choosing which type of graph to get your point across the best is an art form in and of itself now one effective way that i've seen this expressed is by using what is known as a box plot so what a box plot does is it shows the range the maximum and the minimum and the various quartiles and the mean all in one graph well the best way to explore anything is just to explore it let's do it off of the pi plot module there is a function named box plot plot box plot and

130:56 it takes an array so let's give it our array so let's say students gpas and then i'm going to go ahead and do plt.plot that will actually draw it here for us in our notebook check this out students gpas is not defined oh i wonder if that's because i ran the line let's let's try that one more time start and run all

131:29 that looks looked like it worked sorry about that drops us down at the bottom too so we got to get back up to where we were there we go there's a there's our graph look at that it looks like we're doing the right math but it's along the years right so this is one two three four if you remember what our our student gpas look like fourth was all four and these was four three two three nine six let's just

131:59 make sure yeah that's what's happening here so it's along the years instead of along the students this is also a perfectly fine way of looking at things but it's not what we're after so this bottom whisker here is the minimum and the top whisker is the maximum here's the interquartile and this is the the median here it's a bummer that the box plot is graphing along the columns oh wait wasn't there a way to switch the axes of the array like you could go from

132:29 a four to three to a three to four pretty sure it was on that array manipulation dock that we link to in our notes no if you don't remember how to do this why don't you go and find that give me a pause and see if you can't find it in the documentation and get this graph showing what we want go ahead pause me did you find it it's transpose so dot t right on all arrays it will

132:55 actually transpose and we'll switch the order of the array so let's run that one more time beautiful here we go so we've got the three students this is me i was all over the place quasi doing good like we said and here's vlada doing doing well as well got so much better from the start so what do you think we could do with our 100 days of code study minutes i know one of the questions that i get often is how much time do you actually spend doing it

133:22 because you know sometimes it's hard to stop once you get on a roll i'm definitely one to overdo it so let's go down to our study minute so i'm going to scroll down here right about here one way to tackle this is to group your data right now there's a type of graph known as a histogram that will group your data into bins or buckets and then display it it's pretty perfect for what we need actually so remember that we dropped the values that were under 60. so we really just want

133:53 values that are greater than zero so the name of the function is hist short for histogram not like what a cat does when you try to be nice to it so we're going to put in here all of the minutes that are greater than zero actually why don't you do that so i'm going to leave a little to do here for you so when i say pass in a one dimensional array of all the minutes that are greater than zero i want to put this on a new line

134:38 so you got that right you can do that go ahead into this his function pass in a one-dimensional array of all the minutes that are greater than zero go ahead pause me you got this how'd you do did you get it so we can index our study minutes array with a boolean array right and we're going to use broadcasting here because we're going to broadcast this 0 using this comparison operator and that will give us a one-dimensional array of all the values and so we can say plot the plot

135:12 bam look at that there's some buckets that got defined by our data so 25 ish maybe 26 27 times we were in the first range of 60 or so and you could tweak this actually a little bit more but i think that this gets the point across pretty well there's times where i was down here in the the the three hour range but mostly it was up here and then there's even one we went kind of crazy down

135:36 here i hope that you are starting to see and feel comfortable navigating around the wonderful world of numpy you'll see it everywhere like everywhere and being able to use it and understand the terminology surrounding it will greatly help your data journey matplotlib is just one of hundreds of data related libraries that work great with numpy i am excited to see what you do with it you did it you've got another course under your belt great job sticking with it

136:06 i hope that you're able to comfortably navigate the documentation as well as look back on the reflections that you made as you were picking up this versatile library you'll see it popping up in just about every direction you look so i'm glad you got a chance to get your feet wet with it i also hope that you consider taking on the 100 days of code challenge i find it really helps me to stay motivated and learning every single day the community is wonderful and inspiring

136:29 let me know if you do it speaking of community don't forget that you can lean on the treehouse community for just about anything if you're wondering something just drop your question in there it doesn't have to be related to a course just reach out and you'll be greeted with a friendly response it's kind of amazing see if you can't help someone out with a question that they're having nothing helps knowledge stick more than crafting an answer the cheat sheet that we

136:51 built together in this course is available for you to download i've added it to the teachers notes your voice matters your feedback is greatly appreciated and we'd love to hear from you your comments concerns and ideas really do help shape the content that we build here so please keep them coming we want to know what you'd like to see more of as well as where we can improve so please keep us posted on what content you'd like to see as well as what direction you're heading in your

137:15 own personal data journey i hope that you can now recognize the abbreviation when we do import numpy as np as both numpy and no problem this library is huge and can at times seem overwhelming so again excellent job completing this course nothing stopping you now you got this no problem right there are always more courses coming your way so until next time see you real soon

Summary

This course provides a comprehensive introduction to NumPy, a crucial library for numerical computing in Python. It covers the fundamentals of NumPy arrays, their creation, manipulation, and various mathematical operations, emphasizing the efficiency of array programming over traditional looping methods. By the end of the course, learners will be equipped to utilize NumPy for data analysis and scientific computing.

- NumPy is essential for data analysis, scientific computing, and machine learning.
- The library introduces the array data structure, which is faster and more efficient than Python lists for numerical operations.
- Key concepts include array creation, manipulation, and the importance of data types.
- Universal functions (ufuncs) allow for vectorized operations, enabling element-wise calculations without loops.
- Reduction functions like sum and mean can aggregate data across specified axes.
- Broadcasting allows operations between arrays of different shapes, simplifying code.
- Visualization with libraries like Matplotlib can be integrated to graphically represent data.
- The course encourages participation in the 100 Days of Code challenge for consistent practice and community engagement.

Questions Answered

What is the purpose of this course?

The course introduces Python's NumPy library, essential for data analysis, scientific computing, and machine learning.

How can we use lists to store GPA scores?

The instructor demonstrates creating a list of GPA scores, emphasizing the mutability of lists and the ability to append and insert elements.

How do you assign multiple values to an array?

The instructor explains how to use slicing to assign multiple values to an array in a single statement.

What are the methods to add a new dimension to an array?

The instructor shows how to create a new array with an additional dimension using NumPy functions.

How can we filter values in an array?

The instructor demonstrates how to identify values in an array that are less than a specified threshold using comparison operators.

What happens when you slice an array?

Slicing an array creates a copy, allowing for manipulation without affecting the original array.

What is broadcasting in NumPy?

Broadcasting allows operations on arrays of different shapes, applying a scalar value across all elements.

How do arithmetic operations work with NumPy arrays?

NumPy supports element-wise arithmetic operations, allowing for vectorized calculations.

How can we use built-in functions for data analysis in NumPy?

The instructor explains how to use functions like sum and mean to analyze data efficiently.

© transcribe · For agents Built with care and craft by Gokul Rajaram