Section Insights
Introduction to Pandas
What is Pandas and why is it important for data science?
Pandas is a crucial Python library for data science that allows for easy manipulation and analysis of data using data frames, which resemble Excel sheets and database tables. It is essential for tasks like querying, filtering, and preparing data for machine learning.
- Pandas is a must-have tool for data science and machine learning.
- Data frames are the backbone of data manipulation in Pandas.
- Most datasets can be easily converted to or are already in data frame format.
Exporting DataFrames to CSV
How can I export a DataFrame to a CSV file?
You can export a DataFrame to a CSV file using the `to_csv` method. After exporting, you can view the CSV file, which will display the data in a comma-separated format.
- Pandas allows exporting DataFrames to various formats including CSV.
- The `to_csv` method is straightforward for saving DataFrames.
- When importing CSV files, be mindful of how Pandas interprets unnamed columns.
Data Visualization with Pandas
What are some basic plotting capabilities in Pandas?
Pandas provides basic plotting functions that allow for visualizations like line charts, bar charts, and histograms. You can visualize data distributions and trends using these plots.
- Pandas supports various plotting functions for data visualization.
- You can create histograms and other plots directly from DataFrames.
- Visualizations can help in data exploration and understanding distributions.
Creating New Columns with Functions
How can I create new columns in a DataFrame using functions?
You can create new columns in a DataFrame by applying a function across rows. This can be done using a lambda expression to combine existing columns into a new summary column.
- New columns can be created by applying functions to existing data.
- Lambda expressions are useful for row-wise operations.
- You can access individual column values using square brackets.
Filtering DataFrames
How can I filter rows in a DataFrame based on conditions?
You can filter rows in a DataFrame using conditions such as checking for specific values or ranges. The `query` method offers a more readable syntax for filtering.
- Filtering can be done using conditions on columns to retrieve specific rows.
- The `query` method provides a convenient and efficient way to filter data.
- Understanding filtering is essential for data analysis and manipulation.
Transcript
0:00 what is going on guys welcome back this video today is going to be a full Panda crash course for beginners which means we're going to cover everything from scratch the only prerequisite is going to be a basic understanding of the Python programming language now for those of you who don't know what pandas is pandas is one of the most important python libraries for data science it allows us to easily manipulate and analyze data using the data frame
0:21 structure the so-called data frame format and a data frame you can think of it to be a little bit like a combination of an Excel sheet and a database table we have this table like structure and then we have operations like quering filtering aggregating grouping iterating sorting and then also stuff like concatenating merging and joining data frames so it's quite Advanced and we're going to cover all of this in this video today now I would say that pandas is a
0:47 must-have skill a must have tool in your repertoire if you're doing anything related to data science or machine learning it is the backbone of all of this work because most data sets are going to be in a data frame format they're going to either be coming from an API they're going to be coming from a package or they're going to be loaded from a CSV file all of these are either already in data frame format in the
1:08 pandas data frame format or they can easily be brought into a pandas data frame format and that is often times the basis of pre-processing and preparing data for machine learning for training a neural network or for doing basic statistics and data visualization tasks so this is definitely an important skill and in this video today in this course today we're going to cover a variet of topics from basic stuff like indexing and accessing values showing certain parts of the data frame
1:35 displaying the data frame to things like cleaning and iterating and sorting all the way to concatenating merging aggregating grouping data frames so it's going to be quite comprehensive and the goal is at the end of this course you should be able to get started with your First Data analysis project using Panda so that you can put what you learn in this video to practice and try to build something actually useful if you get value out of the video I would really
2:00 appreciate it if you hit the like button and subscribe to this channel to make more videos like this one possible in the future but now let us get right into it AED all right so we're going to get started by making sure that pandas is installed on our system for this we're going to open up a command line and we're going to type pip or pip 3 install Panda so on Windows you want to use CMD
2:29 on Linux and Mac you want to use the terminal if you have pandas installed already you're going to see a requirement already satisfied otherwise it's going to install the latest version of the package now in addition to that this is now optional I would also recommend for this video if you want to follow along that you install Jupiter lab as your development environment I'm going to use this in this video today it's basically in my opinion a superior
2:51 more featur Rich version of Jupiter notebooks which you can by the way install by saying pip or pip 3 install notebook and then you can run ordinary Jupiter notebooks by saying python 3-m notebook or python DM notebook but jupit lap has more features is in my opinion just more convenient has a better UI you can use whatever you want as your development environment I would just recommend that you work with interactive python notebooks use vs code
3:19 use pycharm use Jupiter notebook Jupiter lab doesn't really matter but I would recommend that you work with interactive python notebooks because these allow you to run individual cell of code without having to rerun all of the code from top to bottom which is very useful when you're doing data science or machine learning work because you don't want to have to load the data pre-process the data train the model every time you want to change something about a small print print statement
3:45 or when you want to add an additional print statement so you can run individual cells running on the same kernel I'm going to show you what this looks like in a second here but as I said if you want to have the same environment pip or pip 3 install jupit tolb and then we can use it so I'm going to navigate to my current directory let me just see if I have some files here I don't and I'm going to
4:06 run a Jupiter lab instance here now so I'm going to say Jupiter then space lap and this is going to open up my browser here automatically I'm going to move my terminal here to my second screen and this is now jupit to lab I can look at the file explorer here I can open up a new python notebook so you can see ipy andb interactive python notebook I can call it Main and in here now maybe a one minute
4:34 crash course on interactive python notebooks what I have here is a python kernel that is running so I have a python session you could say and in this session I can run individual celles of codes so I can say xal 10 this defines the variable X now even though I'm starting a new cell now where I can say something like print X even though this is not the same cell the state is shared so I'm running on the same kernel which
4:58 means that print X is going to print 10 now if I run down here x is 20 and then I run this cell here even though it's above that cell it's still going to take that because this made a change in this session in this state and print X is going to be able to get the same variable so that's the basic idea this is particularly useful if we do machine learning work if we do data science
5:21 because often times we want one cell to load a data set maybe it's a huge data set takes 20 minute to load 20 minutes to load then you want to have another cell that trains a model for 2 hours and then you want to have an evaluation function and then you want to have some basic print statements and if I want to add an additional print statement I don't want to be running all this code again I just want to keep the trained
5:41 model and keep the loaded data set in Ram and then I want to just use it down here so that's the main benefit and when we do pandis work when we do matp lips iy could learn pytorch any machine learning data science data visualization stuff it's just more convenient to use interactive python notebooks so let us get started with pandas what we want to do first is we want to say import pandas as PD this is going to import pandas
6:05 with an alias of PD the only effect of that is that instead of saying pandas do whatever function or class I want to use I can now say PD do whatever function or class I want to use so it's just a synonym and Alias and that's the best practice way the conventional way to do that basically every code example that you find will say import pandas SPD it's just a shorter way to write pandas and I
6:28 want to get started now for this course with the two data structures that are the backbone of pandas everything else will be based around those two especially around the second one these two are the series and the data frame now I already talked about the data frame in the introduction it's a little bit like a combination of an Excel sheet or a database table and a database table basically we have this table structure and then we can filter
6:52 query iterate sort group merge concatenate join and so on with these data frames and a series can be considered to be a column of a data frame so every column of a data frame is a series a series is a little bit like a python dictionary I'm going to give you an example right away let's say we have a list of values 10 20 30 40 50 and then I create a series based on these values I can store
7:19 it in a variable s for example when I display that you can see I have the values and I have the so-called index here so I have the labels I have 0 1 2 3 4 by default but I can also go ahead and say that I want to specify my own custom index for example I can say I want to have a b c d and e and then I have these letters as my index and compared to primary Keys
7:49 in databases and also compared to keys in dictionaries here I can have duplicates so I can say a b c d a this of course has the effect that when I look up something based on the index so when I want to know what a is I'm going to get two rows so we're going to talk about this a little bit later on in the tutorial but for example with lock I can access based on the index so this is
8:13 a an indexing attribute basically and what I'm getting here is A10 and A50 because there's a duplicate here so this is possible but indexing is in general something that is made for performance so by using the index I can quickly access individual roles that's the basic idea so this is the series and the data frame is now a you could say a collection a concatenation of series basically one series could be names another series could be ages another
8:44 series could be jobs and all of this taken together could be forming a data frame so let's see how to create a data frame I can say DF is equal to PD data frame like this and I can pass here a dictionary where each key is a column name for example name and the value is a list of values so I would say name could be Mike Bob and maybe Alice for example then age
9:15 could be something like 30 80 45 and job could be programmer clerk designer for example so this would be dictionary these are the column names these are the row values so to say and when I just run this and I then show the data frame here you can see I have this table like structure I have name Mike Bob Ellis I have age 30 80 45 I have job programmer
9:45 clerk designer and you can see I have an automatic index going from zero to two because I have three rows here I can also change that either by specifying the index here manually as well like I did up here or I can now I'll say take one of the columns and make them the index so I can say DF is equal to DF do set index and then I can say for example name this would set name
10:09 to be the index column so now I could identify the rows by name so if I use the lock function again or actually it's not a function it's an IND indexing attribute but if I say DF lock mik I can do that now because mic is an index value because name is the index the important thing is also you want to do do always DF equals DF set index you don't want to do just DF set index
10:34 because it doesn't do anything this is just returning a data frame where the index is name but the actual change is not applied to the data frame unless we say DF equals DF set in index so we have to assign it because otherwise it just Returns the new data frame there is a workaround or not necessarily work around there is an alternative to that you can theoretically say in place equals true then you don't have to
11:00 return then you can just say DF set index but that is considered a bad practice we don't want to do that it is possible I want to show that to you but the best practice way to do that is to say DF is equal to DF set index and to do it like this one thing that's interesting is that the index is used for alignment when we do arithmetic operations so if I have two data frames
11:24 let go now with different data frames df1 is Panda data frame frame and let's say I have I don't know the column A with the values 1 2 3 and then I maybe have a data Frame 2 Data frame with a column B here or actually with a column A again and now I have the values 10 20 30 if I just do it like this and I say df1 plus df2 I will just get 1122 and 33
11:56 because they have both 012 as index but if I say for example here now that the index here is going to be 012 so the default and if I say that the index down here is going to be 1 to 0 for example so a different order you're going to see that this also changes because now what's happening is one is being added to 30 then two is being added to 10 and three is being added to 20
12:25 because what happens automatically when we do stuff like addition multiplication and so on is it's aligned based on the index so that's important to understand that's important to know but yeah so what we can do now with data frames and this is where stuff gets interesting is we can export and import using different data formats so I have this data frame structure this table like structure here DF and what I can do now is I can export this into CSV
12:54 files I can export this into a Json format I can export this into an Excel sheet I can export into HTML and into many other formats maybe just to show you how to do that here I want to reset the index first so resetting the index means we're going to make the index to an actual column so you can see that this is what happens here and I get my default index back so I can say DF is
13:17 equal to DF reset index and now let's say this is what I want to export into a CSV file how can I do that I can do that by saying df2 and then I can use tab for for autoc completion here and you can see that I have all these different formats I have CSV dictionary Excel I have HTML Json markdown I have parquet I have pickle I have SQL I have XML so I have a bunch of different
13:44 formats that I can export my data frame into and I can say here to CSV my data.csv for example when I run this and I refresh my file explorer here you're going to see I have this CSV file this is now displayed as a table so let's go into the terminal navigate to the directory here so caty data. CSV you can see that this is just a comma separated value file so I have name H job Mike Bob Lis 30 80 45 and so on and
14:16 I have this unnamed index column so you can see I have here an empty column but I have a comma so there is a column and I have 012 now this is important because what happens when you try to import a data frame is that this is also considered to be an ordinary column so how can I import a data frame I can say pd. re and then I can use tap again to show all the
14:39 different formats I have CSV Excel HTML Park and so on and if I say read CSV my data CSV this is going to be a data frame but as you can see now I have name H job then I have this unnamed zero column this is just pandas recognizing the column is unnamed but I need name so I'm going to call it unnamed zero and now I have here my values and in addition to that I have now a new index
15:07 column which is of course not what I want so what I can do here is I can say index column is equal to0 to specify that the First Column of the CSV file is actually the index column like this I can also say the index column is one in this case name would become the index but I would still have my unnamed zero here so in order to get rid of the index while exporting the file I can
15:29 also say here that the index is equal to none this is going to basically export it without index so now I only have name AG job this is not the index this just the row here so we can open this up again and you're going to see that now I have name H job Mike 30 programmer Bob 80 clerk Alis 45 designer so I don't have this unnamed index column which means that I don't have to specify
15:55 that this is the index column or I can say index column equals zero to say that the name is now the index so and this can be done with a number of different formats so I can say df2 Json I can do the same thing here my dat. Json here what happens of course is that the keys are the index so I have 012 012 here as index and then I have this Json format again maybe to show it here in
16:23 terminal this is what it looks like then we have this Json object name Ag and job and we can do the same thing also with two dictionaries so I can say DF do2 ditionary this turns it into a python dictionary which is basically like the Json object but as a python object now and so on and so forth we have different formats that we can choose from just to and whatever you want to choose here and from and
16:50 whatever you want to choose in the case of HTML for example it exports a table structure into HTML format so it's quite compatible with different data sources now what I want to talk about next is how we can take a look at data frames and for this I want to do something else I want to get rid of all of this here and I want to import an actual data data set so not just my own three rows I want to show you an
17:15 actual data set that you can get from a package now you don't need to use this one if you don't want to but I'm going to use a data set from pyit learn if you want to also use the exact same data set you need to install pyit learn but this is just for demonstration purpose purposes so there's no need to do that you can say pip or pip 3 install scikit-learn and I would also recommend
17:35 installing Matt plot lip because we're going to do some visualization as well so these two packages if you want to follow along with the exact same example and now I'm going to say from SK learn. dat sets we're going to import fetch California Housing so it's not really important what kind of data set this is it's just a data set that is going to have some color colums and some rows and what we can do is we can say that
18:02 the data is equal to fetch California Housing as frame equals true this is going to then have an attribute. frame and that is going to be our data frame so I can say data and you can see I have this pandas data frame here now that I can work with so maybe let's call it DF and again it's not that important what kind of data we have here you can see this is just some data set all of
18:31 these values are numerical which doesn't have to be the case as we saw with the name we can also have text values and dates and so on but in this case now all of this is all of this is numerical what I can do now is instead of looking at all of this data set of the instead of looking at the whole data set which has 20,600 rows and nine columns what I can do is I can get the first couple of rows
18:56 so I can say DF do to get the first five rows just to get a feeling of what this data set looks like I can also say DF do tail if I want to get the last five rows and I can also say DF doad 10 for example to get the first 10 rows or of course DF tail 10 to get the last 10 rows in addition to that I can also do sampling so I can say
19:21 DF sample to get one random Row from the data frame this is just any row randomly picked so I can run this all the time every time I'm going to get a new row and I can also say sample 10 to get 10 random rows which could be a more representative thing than just looking at the first 10 rows so these are just the basic three methods that you can use for exploring data sets if you want to just take a look at the
19:47 first couple of rows the last couple of rows or a couple of random rows just to see what does this data set look like in general also sometimes you're going to have more columns than just how many do we have here nine so you might have you might want to actually get a list of the column names for example you might want to say DF columns and take a look at that you can also turn this into a
20:11 list and then you have a better overview especially if you have a lot of columns because some data sets have 100 columns and then of course it's a little bit difficult to just see everything in a data frame also what you do often times have is you have a display limit so right now we don't have it but in this case I have 9 columns sometimes I might have 100 columns and it's not going to show all of them and what you can do in
20:34 this case is you can use the options of pandas to change that limit so I can say pd. options. display Max columns and in this case if I set this to five for example you're going to see that I see one two and then this dot dot dot column four five columns and if I want to change that I just have to set this 2 500 for example in this case it will show all the columns now sometimes you might be
21:03 interested in more general information in this case you can run DF doino this is going to give you information about the data frame in a more concise manner so you're going to see the column names you're going to see how many missing values you have so in this case we have 20640 entries and in each column that is how many non-null values we have so this is a complete data set but sometimes you might have certain features where you
21:27 only have 100 non-null values then for example for machine learning it makes sense to drop that column or ignore that column sometimes you might have three or four missing values in this case it might might make sense to drop these rows or to fill these rows so we're going to talk about this in a second as well but this is a nice overview to see okay which of the features are complete how many of them are lacking values
21:51 how many of them are lacking a lot of values you can also see the data types in this case now we only have floats but you can see here string integer float object in general in data frames you are allowed to mix types but you will end up with objects if you do that so if you have only floats you're going to have the dtype float but if you have for example integers floats and strings you're going to end up having the object
22:16 data type so you are allowed to mix data types but it's going to make a difference in terms of performance so what I want to also show you now is a couple of statistical functions this is why it CH this data frame because we have a bunch of numerical values in here and I want to show you how you can use that or how you can easily get information about that in pandas and the first function I want to show you is the
22:38 describe function because that is the best overview you can get you can just say DF do describe and it's going to summarize all the statistics so what we have here is a data frame itself which gives us for each feature now each feature here is a column and the index here is you can see the different metrics so the count how many instances of this do we have so how many non-null values this is basically the same as up
23:04 here but also what's the mean value what's the standard deviation what's the minimum value the maximum value and then we have these percentiles here which we can also take a look at to get a feeling of the distribution the statistical distribution this is like a dashboard you could say you get the data frame and you want to see okay in one simple view here I can see how the individual features how the individual columns are distributed and what they
23:32 basically look like that is a nice overview but you can also get the individual information for each column so what I can do is I can say give me one specific column if I'm for example interested in the house age specifically I can say DF do house AG DF do house Ag and that is going to give me a series you can see that this is now a series I can run the type function on it and that is now a panda series
24:01 because a column of a data frame is a series and I can now run different statistical functions on this column on this series also another way to access that would be using square brackets I can say house AG like this this also works so doesn't really matter what you want to choose here and now you can run a bunch of statistical functions like mean for example what's the mean House age value there you go what's the smallest house
24:31 AG value one what's the largest value 52 what is the standard deviation 12.58 what is the median 29 what is the mo so the most common value 52 or no actually yeah 52 what is the do I have something else what is the count what is the sum the sum would be all the is summed up together now in the case of H maybe it doesn't make a lot of
25:01 sense but with other features it might make sense so you can use these functions on individual columns to get aggregated information to see okay what's the average value what's the median what's all of these values summed up together in the case of a price maybe product prices or something like that we can do all of that quite easily I can also easily visualize this as a plot so I can visualize the distribution of the house house AG as a histogram just by calling
25:31 the hist function so this uses mpot lip behind the scenes if I say DF house AG hist what happens is I get a histogram using matplot lip and if I want to customize this histogram I have to work with matplot lip so this is optional now you don't have to do it but you can import matplot lip. pyplot spt and you can say stuff like for example PLT title house Ag and then I can say PLT
26:02 show and now you can see I have a title in my plot so this is just using M the behind the scenes you can see the distribution here I can also pass arguments like the figure size and stuff like that so I can say 128 make it larger so all of this is very very simple with pandas I can also use by the way different plot types I don't think it makes a lot of sense now but I can do
26:30 plot and in this case it would get it would produce a line chart as I said doesn't make a lot of sense but we could also do plot. bar which also wouldn't make a lot of sense I guess I think this might actually crash crash the the visualization here but I can do stuff like plotting bar plotting Pi I can run the I can call the individual mat plot lip functions just by using the feature. plot do plot type and I can use
27:00 histogram as well now I can also do that by the way for the full data frame I can say DF doist to get a histogram of the full data frame so you can see I get for each feature a histogram I can also say here again figure size is equal to 12 and 8 and I can maybe say something like PLT tight layout there you go and now I can see for each
27:31 feature how it is distributed and I can see that some of the features have something approximating a normal normal distribution and the others not so much so that's very nice as well to do some data exploration and of course I can do DF plot as well doesn't make a lot of sense maybe but I can do that if the data set makes sense if this is stock information for example we could do that by the way let's actually do
27:59 that we can visualize some stock information I'm going to use the Y Finance package for that import y Finance as YF this is again just an example if you want to do the exact same example pip 3 install y Finance but you don't need to install all the packages here these are just some basic examples I want to show you that Panda data frames are quite common so if you use the Yahoo finance API to download stock information so YF
28:27 download AAP L for Apple what I get here is a data frame so this result that I get from the API is actually a data frame let's call it stock DF and this stock DF has open high low close adjusted close and volume volume and I can say now close. plot for example this would make more sense because now I can see the stock price I can also say just plot everything in general now with the
28:58 volume it doesn't make a lot of sense so maybe we could just plot the other features we're going to learn how to exclude features or how to select a subset of the columns in a second here but that would work and here as well we could maybe that doesn't make a lot of sense now but we could do a histogram yeah that's that's something that you can do here with stock data as well so let us now talk
29:22 about the access which I just talked about how can we select specific columns how can we select a subset of columns how can I select specific values in a data frame like targeted this specific value or this specific row how can I do that efficiently what are the best practices so for this I'm going to go down here let's see what we currently have in DF it's still the California Housing data frame now actually what I want to do if I have it still here no
29:48 I'm going to do it again from scratch I'm going to work with my previous data frame so I'm going to say data frame I want to use again name Mike Alis Bop and then H is going to be 30 45 and 80 and then for job what did we have for job I think we had programmer designer clerk no we had accountant all right so how can I get one specific Row
30:22 from this data frame now we already talked about this we can do that with the lock indexing attribute so I can say DF dolog and I can refer to the index to get this particular row so in this case my index is just 012 so if I say lock one I can get Alice because Alice was at position two so Alice is index one that is Alice so this is what I get when I say lock
30:48 one now if I say that my data frame is going to be let's say DF is equal to DF set index name if I want to do that I can say now that my index is Alice and I will get the exact same row because this is now indexed using the name now what I can also do even though now that my index is a string I can use iock which is basically an integer
31:21 indexing attribute so I can say ick and I can still do the same thing I can say this is row zero Row one row two and I can just say iock one to also get Alice this is also possible now I can also say that I'm not just interested in Alice I'm also interested in a specific column of Alice so I can do the indexing here on the row basis and then I can also select a specific attribute and then I
31:45 could say DF lock Alis and then H in this case I would get the specific field Alice H which is 45 so when I run this I get 45 I can do the same thing with iog I can say I want to have the Row one which is the second row and I want to have the column zero so the First Column this is not a column this is the index that would be the First Column and in
32:10 this case I would also get 45 now for this we actually have a better way because there is a function or there are two functions called at and I at which are like lock and iock but for scalers for individual values they're optimized for that so if you're trying to get a specific value if you're just trying to get one value it would be better to use at so in this case if I say DF at Lis and H I will get the exact
32:40 same result also when I say I at one and zero I'm going to get the same result so that would be the preferred way if you're targeting one single field an exact value but these two functions are not able to handle full row so I cannot just say say DF at Alis this is not like DF loog Lis this has this doesn't work because we need to have one specific value not an entire row so that's the ma major difference here we
33:10 can also use this by the way to change stuff so I can say actually that I want to change the age of Alice I can do that by saying DF at Alice H and I can set that equal to 60 for example and then we have 60 instead of 45 I can also do that with the entire row if I say DF log Ellis that is going to be equal to let's say 75 she's always getting older and
33:40 now let's sh let's say she's a clerk now I get 75 clerk so we can also use this to make changes not just to get information what we can also do is we can append new rows like that so I can say DF log and then maybe a name that we don't have yet something like John JN can also be someone who is 90 years old and let's say he is teacher we can do that as well and this
34:10 adds a new row John 90 and teacher now another thing that's maybe interesting to mention is that we can use slicing with these indexing attributes so I can say DF iock for example and I can go not only to index zero I can also say index zero up until index index two so it would give me these two rows because the last one is not included so I would get zero and one if I want to have 0 1
34:34 and two I would have to say 0 to three so this is also possible and I I can also do that for the individual axis so I can say that I want to have 0 to three but I only want to have one so I only want to have the second column so we would get programmer Clerk and accountant because that is the column two the drop column and I want to have the first three rows now I can also say
35:01 I want to have all the rows by just passing a colon so I can say iog colon one this would give me all the values all the rows but only column one and I can say of course give me everything by just saying colon colon that would be just like printing the data frame itself but of course I can say give me everything from row zero or give me everything from row zero to row one but
35:24 this doesn't make a lot of sense because in this case I could just say do it like this now we talked about how to manipulate individual cells how to change the value of individual cells now let's take a look at how to do that with entire columns and rows one very simple way to do that is to just take a column like for example the H column and do some basic operation with it for example dfh * 2 this would take the H and double
35:48 it or we could do to the power of two that would take the square of the H and if I want to store that back into the H I could just say dfh is equal to dfh H * 2 and now this is applied to the data frame so that would be a very simple transformation of course I can do it the other way around as well dfh is dfh divided by two and then I have the
36:09 original data frame again but now I have a float because a division results in a float so that is quite simple but how can I do something more interesting how for example can I do something with conditions how can I do something like get all the ages that are divisible by three for example and for those Square them for the other ones do something else how can I do some more complicated logic I can do that by using
36:34 functions so for example I can say my function I Define my function down here and this function will take an individual row or an individual instance as a parameter for example let's call this x so this function X shall do the following thing if x is divisible by three for example let's say we want to return X to the^ of 2 otherwise we want to say x should be divided floor divided by two and returned so this is a very
37:05 simple function you pass a value X into it if x is divisible by three you get the square of that value otherwise you get the value divided by two floor / by two now I can take this function and apply it to the H column so I can say dfh do apply this is now a pandis function and here now I just have to pass the function function as an entity so I don't call the function I just pass
37:30 the function as an object and what happens now is that this function is applied to the ages so you can see these ages here were squared this one was halfed because Bob was 80 80 is not divisible by three all the other ones are divisible by three because of that they are squared otherwise or not otherwise Bob was half that's a very trivial function now but this is how you can basically do that you Define a
37:57 function it doesn't have to be a numerical one by the way you can also say let's call this my function 2 it's going to take a value X and if x starts with let's say x is a string or actually let's say ends with because otherwise we don't have more than one example ends with R like teacher or programmer if that's the case we're going to just say that this person is going to
38:28 be without job otherwise we're going to just return the job that existed before so I can say DF job apply my function 2 and you can see actually I do have oh we need to return X of course so you can see I have clerk accountant and then without job for the two that ended with an r and of course this is not not apply to the data frame you need to actually store this so
38:59 you need to say DF is equal to that or actually this is now I now messed this up this doesn't work of course because now I set the whole data frame to that so I'm going to I'm going to run this again so what I want to do is of course I don't want to apply and set this to the data frame I want to set this to the job column so now I have without job without job and I think that
39:22 Alice is now without job because I had before she was designer and designer is also with an R so yeah but this is how you can apply individual functions if the function is quite simple you can also do that as a Lambda expression you can say the H for example we want to apply some change the change is Lambda taking a parameter X and returning X to ^ of 2 that is also possible now this would be quite simplistic let's say
39:48 if x is divisible by 10 otherwise just return x / 2 so again we can see how this is applied now we can do the same thing also for the entire data frame on a row by row basis so instead of taking just an individual value from a single feature we can also take the whole row and choose the features of the row that we were interested in to craft a new row or to craft a new column
40:12 actually so we're going to say data frame I have now the job and DH so what I want to do maybe is I want to have a summary which combines H and job into a string this is now a very simple example but let's say I want to create a new column summary column and this column is the result of applying a function to the whole data frame it's going to be a Lambda expression the Lambda expression is
40:34 going to get a row is input and this row should result in a formatted string where I say it's going to have H colon row H and then jop colon row jump just a simple example then I can close this and the important thing now to say that I want to apply this on a
41:05 row by row basis I need to say axis equals 1 so by doing that I now have the summary column which took H and job and combined them into a summary column this is again a very simple example but this is how you can craft this you can also Define of course a full function you can call it row processor or something taking a row as input doing something and then returning something and you can access the individual columns here using
41:32 square brackets like in a dictionary so the row is just one row a series basically and you can access the individual column values now another thing that you might be interested in is how can I drop columns how can I remove columns that exist in my data frame for example maybe I think the summary is not necessary I want to get rid of it how do I do that that's quite simple you just have to say drop and then the column
41:56 name summary but you need to do that providing axis equals 1 so you need to say drop summary axis equals 1 and that is going to drop it it's going to remove it however keep in mind again this is not applied to the data frame you need to actually say DF is equal to DF drop summary and then it works now you can also say drop multiple columns in this case you would have to pass a list so
42:20 you could say something like H and job because the summary is enough for example AIS equals 1 and now you have only name and summary so this is how you can do that as well if you want to drop the index you would have to first reset the index drop name and then you would have the new index which is the automatic index from zero to length of your array data frame now let's move on to data cleaning what do I do if
42:46 I have some invalid values in my data frame let's say I have this data frame and one of the ages happens to be a not a number value a nan value I can do that by saying at Alis set the H equal to float Nan so not a number and if I look at my data frame now you can see I have a nan value in here also when I call the info function you're going to see I only
43:16 have three non-null values out of four entries for the h column so here I have some missing value here I have something that I cannot cannot work with and now I have to choose what do I want to do with that missing value so one way to handle missing values is to just drop the rows so I can say DF drop na a this is going to drop all the rows that contain Nan values so now Alice is no
43:41 longer part of this data frame I can also say that I want to fill the Nan values so if I fill the Nan values this is going to replace the not a number value with something else for example zero so this case now Alice would have an age of zero not of Nan and now I have again all the values that I need I can also say ne-1 to make it clear that this cannot be true this has to be a mistake
44:08 but I still have a valid value in here I can also do something more intelligent I can say that I want to fill maybe with the mean h with the average H so I can say DF fill na a or maybe I can say DF Doh fill na a and then I can use as the value to fill it with d f.h. mean in this case I would get 66. 666 so that would be at least something
44:35 that doesn't destroy the mean statistic it would be the same afterwards so you can think about this how you want to handle this also sometimes you might want to drop Nan values in one column but not in another column how can you do that well you can let's say for example I want to set something else to Nan let's say that for for Bob I want to set the job equal to none this of course works you can see now the job has
45:08 also only three non-null values and if I now say drop an a it's going to drop both rows so if I just say drop an a it's going to drop Bob and Alice but maybe this is not what I want maybe what I want to do is I want to drop only the rows where the H is none I don't really care about the drop in this case I shouldn't be using drop and a I should
45:27 be using the not na a function so I can say DF not na a and you can see I get the true and false booleans here for the individual cells you can see here I have false because it is an A so it is not a number and here I also have something that is missing and I can use this now I can use these booleans now to filter for the rows where this is not the case so I can say this is
45:54 now something that we're going to learn about in a second here when we get to filtering but I can say give me the data frame where DF Doh is not an A so that would give me still Bob even though Bob has none as the job but it drops basically all the rows where H is not a number and in this case that's Alice but we're going to talk more about this notation in a second here before that
46:19 let us move on to iterating how can we iterate over our data frame how can I use a full loop to go through the the individual rows in my data frame or through the individual columns this can be done with something called it rows I can say DF do iter rows and that gives me a generator object so I can iterate over it to get the individual row I can say four index and row in DF iter rows
46:48 and when I print I you're going to see I get the index so the name Mike Alice Bob John and when I print row I'm going to get the serious object which is the row so I can get AG job summary and I also get the index here so I can say row and summary for example so that would be a row-wise iteration I can take the data frame go through the individual rows and within each iteration I can access the
47:14 individual column Fields if I want to do it the other way around if I want to iterate over the columns and get the individual rows I can do DF do items so if I say DF do items that would now be a column I can print I you can see the I now in this case is I'm getting the column name so H job summary and the column itself is for the respective person so I get the First
47:44 Column being H Mike has 30 Alice Nan Bob 80 John 90 before it was I had Mike Alice Bob John and then the individual columns now I have H job summary and the individual names per iteration so in each iteration here I can access individual row identifiers now let us get to the more interesting stuff how can we filter how can we query data frames how can I get specific entries from the data frame based on conditions
48:11 I Define to understand how this works we need to understand that everything here is based on booleans now if I say something like dfh being larger than a certain value like being larger than 50 for example that is going to give me a series full of booleans now for Alice I'm going to get false because she has an N value for Mike I'm going to get false because Mike is 30 years old so I'm going to get false false true true
48:37 these booleans now are used to get the data from my data frame so if I just go ahead and say DF square brackets and I pass a list of booleans this exact list false false true true I'm going to get the entries Bob and John because that is what I'm saying here I don't want to have Mike I don't want to have Alice I do want to have Bob I do want to have John and instead of writing this
49:06 manually I can just write conditions that do exactly that so dfh being greater than 50 is going to result in all the columns in all the rows sorry where the H is larger or greater than 50 now I can do the same thing with combinations so I can say the H has to be above 50 but also I'm going to use this ant now I'm going to use parenthesis here I'm going to say this is one condition logical an and I'm
49:33 going to say the other condition here is that let's say job is not an A so now I want to say the age has to be above 50 but the person also has to have a job that is not none now without a job might be jobless but it's not a none value so it's actually a valid value and in this case I'm going to get false false false true so I can take that I can say DF
49:59 give me that and I'm going to get only JN because JN has an age above 50 and he has a job value that is not none so this is how you can chain these things you can also say by the way or a logical or would give you all of them because all of them either have an age above 50 or a job value that is not none so in this case that works quite well and also what we can do is we can negate
50:25 stuff so I can say say give me all the rows where the job is not none but I can also say negate that by using a wave here I can say give me all the rows where the job is in fact none so I can run this and you can see I only get Bob if I negate this so basically flipping all the truths and falses to be the opposite now there are certain data types where we can do more than just
50:48 compare for being greater than something or being equal to something we can do stuff like for example if something is a string if I have for example the name let's turn the name into a column I'm going to do this by saying DF is equal to DF reset index now I have the name as a column what I can do now is I can say give me the data frame rows where the name and now I want to say the name has to in
51:16 this case doesn't make sense to say starts with so let's say ends with an E I want to have the rows where the name ends with an e in order to be able to do that I need to say I want to treat the name as has a string so DF name. st. ends with and then e so that is going to give me all the rows where the name ends with e this is Mike and Alice
51:39 and now I can change it chain this together I can say that and dfh not an a for example and I can combine these queries like that to filter out the columns or the rows I'm interested in another special data type would be the date so if I say import datetime sdt what I can do is for example I can create a column birthday and this column we can even derive that from H so I can say take the
52:09 H and apply the following expression to it take a Lambda expression take the H's input X and then I'm going to say DT date time. now minus DT time Delta days is equal to 365 days time x so time H and that should give me a date I hope of course this doesn't work if I'm having Nan value so let's actually go ahead and
52:41 say let's actually go and say Phil DF is equal or dfh is equal to dfh fil na a let's just say 30 like this and now let's run this again and you can see I now have the date column here now with dates I can also do certain things for example I can say get me all the people all the rows where DF dob birth.
53:12 dt. year this would be one thing that I can do is greater than 1950 that would give me two rows Mike and Alice because they are 30 years old and not 80 or 90 years old in general another thing that we can do is we cannot just check for ranges we can also check if something is part of a collection so for example if I say ages I can say I accept the ages 30 and I
53:37 accept the ages 80 and then I can say give me all the rows where the age is in so it's part of Ages and in this case I get 30 30 80 because they're part of the ages list but I don't get 90 and this also works if I go with 90 instead of 80 so I can exclude values in between just because they're not part of the list so this is also something that we can do with numbers with strings with
54:02 anything essentially and that's quite convenient now everything we just did can also be done with a method called the query method this is basically an alternative to this filtering syntax so we don't have to use the square brackets we can also set DF query and in a string here I can say for example H has to be greater than 30 this on the one hand can be more convenient in terms of the syntax so maybe that's more readable and
54:28 more convenient to write for you but also it is faster when it comes to larger data frames because it uses num expers so numerical expressions behind the scenes here which makes a difference if you have huge amounts of data so that can be reasonable in terms of performance it can also be reasonable in terms of readability however it is to some degree limited you cannot do everything with query that you can do with this filtering syntax but if you
54:55 want to use it if you feel like this is a better way to do that if it's more readable to you that might make more sense so now let us move on to grouping what is grouping how can we group data well grouping makes sense if you for example have similar values in a column let's say in my data frame here or in our data frame here let's say that all the Jess people actually let's give
55:18 Bob a job let's say DF job fill in a let's make him a programmer let's say DF job is equal to that so what we can do now is we can now the summary is of course incorrect so let's drop that DF drop summary like that there you go so what we can do now is we can calculate metrics we can group them together we can group all the people without job together and calculate certain
55:48 aggregated metrics so for example I might be interested in what's the mean age what's what's the average age of the person without a job so I can say DF Group by and I can Group by job this is going to give me a group by object and to actually get a data frame out of this I need to aggregate it in a way so I need to say for example Aggregate and now I can pass a dictionary where I say
56:16 that the H for the h i want to do the following operation mean so what this does is it groups the People by job and it results with an age column here that takes the average of the ages of the people of these categories so for example if I have the data frame and I add an additional row here let's say we need Jane now actually I should say probably DF lock in this case four since
56:44 the index is now a different one again is going to be Jane 35y old let's say also programmer and she's also going to have or she's not going to have a birthday let's do it like this and not a time this is basically like not a number for date for date columns but basically now what we can do is we can do the same group by operation so I can copy that or I can actually take the cell drag it down
57:10 here run it again and you can see that this affects the average age of a programmer so we're taking these people together in this case Bob and Jane 35 and 80 and we're taking the mean of that so 80 + 35 ided 2 that is going to be exactly what we see here 7 57.5 so that's the basic idea of grouping we group together based on similar values all the people without a job are one group and then I can
57:40 calculate different metrics for different columns what I can also do is I can specify multiple metrics so maybe I'm interested in the average age of the People by job I'm also interested in the Min I'm also interested in the max maybe I'm also interested in the sum for for whatever reason I can do all the aggregation functions here and I will get them as individual columns so I know now that the average age of a programmer
58:04 in my data set is 57.5 the youngest programmer is 35 years old the oldest programmer is 80 years old and for whatever reason I need to sum but this basically gives me a nice overview and I can see what is happening inside of these groups there's also some more advanced stuff that you can do you can take these groups and apply custom aggregations by using apply and applying custom functions onto entire groups but this is a little bit too advanced
58:29 for this crash course today if you like this video I'm going to make a more advanced pandas course as well so if this video gets a lot of views comments likes whatever I'm going to also make an additional episode on more advanced stuff but for now we're going to leave it at that this is the grouping that we're going to be mainly focusing on so the main idea is I can Group by columns and I can then apply
58:52 aggregations I can then say give me the average min max summon and so on so let us move on to sorting how can I sort the values of a data frame this is not too difficult I have my data frame and now I want to sort not by index but by H how do I do that I say DF sort values and then I pass H that's basically it now I have the H in ascending order if I want
59:15 to have it in descending order I have to say ascending equals false and then I'm going to get 90 80 35 and so on so that's quite simple now the last topic I want to cover in this crash course today is merging concatenating and joining data frames and for this I'm going to use a different example I'm going to use an example that I have prepared here and it's going to be data frame one data Frame 2 I have the items AB BC DF and I
59:43 have the prices 10 20 30 40 50 60 I have these two data frames in my goal list now in this case one data frame looks like this I have some items and a price and I have some items in the price here in data Frame 2 as well and all I want to do here is I want to Stack the rows I want to have all these in a single data frame they don't need to be joined in a
60:05 fancy way I just want to have a b CDE e f 10 20 30 40 50 60 how do I do that this is done using the pandas method called or the pandas function which is called concatenate so pd. concat and what we do here is we pass a list of data frames df1 and df2 and basically if I just run it like this you're going to see that I already get a B cdef 10 20 30 40 50 60 I can also say
60:39 reset index to basically get the index again from 0 1 2 3 4 of course then I have this index column which I would have to drop so I can have I can say drop index and that would give me or I need to say AIS one of course that would give me now the data frame a b CDE e f 10 20 30 40 50 60 with the correct index so that is how you can
61:07 stack rows now you can also stack columns for example let me show you that I have two other data frames prepared here let me copy them as well if I have the data frames ABC 10 20 30 then I have country XYZ and available true true false d are two completely different data frames but I can concatenate them I can throw them together as long as the index is the same so if I have these two you can see
61:35 df1 has index 012 df2 has index 012 but they have completely different columns easy I can just say PD concat df1 df2 and then this actually I need to say axis equals 1 and now you can see I have item price country available stacked together columnwise now the interesting stuff happens when I introduce a data frame like this one let's say I have data
62:07 frame three and I want to join or I want to merge data frame 1 with data frame three so I have this one I have this one and what you can see now is I have a common column item which has ABC here and BCD here here I have the price information here I have the country information and I some how want to merge these two data frames into a single data frame how do I do that I can do that
62:32 with a PD merge function so I can say PD merge and here now I can say data frame 1 data frame 3 and if I just do it like this you can see that what happens is it does an inner merging which means it takes what they have in common B and C because we have AB c b c d a occurs only here D only here we take what they have in common b c BC and we merge it
62:56 together so we get b2x and C30 y combination of B20 BX and c30c Y but what if I want to have all the rows still there but if there is no value if there is no complement just leave it empty just set it to none have a missing value there it's fine for me how can I do that we can do that by specifying the how parameter I can say how is equal to to Outer and this is going to
63:26 result in keeping all the items a b c d but the country is missing for a and the price is missing for D so we accept these Nan values because we want to keep all the values if I set this to Inner this is going to be the default so this is what we had by default if I say outer this is going to be everything if I say left it's going to keep everything from the First Data frame and not from
63:50 the second data frame so it's going to be ABC leaving the country here as Nan and if I say right it's going to keep D but not a so it's going to be B C D and it's going to have Nan for the price also theoretically we can specify what column we want to be merging on in this case now item was obvious because it is what they have in common but sometimes you might want to specifically
64:15 say I'm merging on the item column so you want to do it like this item outer for example and then you're going to be able to merge the data frames now if you want to join on the index you can do that also in a different way so let me use one more example from my prepared code we're going to use df4 and df5 here what we have is we have the price and the country and then we have the index
64:40 information ABC BCD and now we can do the same thing df4 this is now not a pandas function but a data Frame data frame method so df4 dojin df5 if I just do it like this it's going to do just a basic left joint so that's the default the default is how equals left in this case if I want to do an inner joint as before as with the merging I can say inner this is going to give me
65:10 what they have in common so B and C if I say outer it's going to get all four and if I say right I'm going to get BCD so same idea difference is we're doing it on the index and I can call it as a data frame method so that's it for this Panda crash course today I hope you enjoyed it I hope you learned something I hope this was helpful to you if so let me know in
65:31 the comment section down below and by hitting a like button depending on how you guys respond to this video depending on how many views and likes it gets I'm going to maybe consider making a more advanced Panda tutorial as well this was now focused on speed focused on Simplicity on the basics the goal was to keep it concise to deliver the value and the knowledge as quickly and as simply as possible if you guys want a more
65:54 in-depth tutorial for focusing on more advanced concepts let me know in the comment section down below and I might consider doing that in the future besides that don't forget to subscribe to this Channel and hit the notification Bell to not miss a single future video for free other than that thank you much for watching see you in the next video and bye
Summary
- Pandas is a crucial Python library for data science, allowing for easy manipulation and analysis of data using DataFrames.
- Key data structures in Pandas include Series (a single column) and DataFrames (a table-like structure).
- DataFrames can be created from dictionaries, CSV files, and other formats, and can be manipulated through indexing, filtering, and aggregation.
- Essential operations include sorting, grouping, merging, and concatenating DataFrames, which facilitate complex data analysis tasks.
- Data cleaning techniques such as handling missing values (NaN) and filtering based on conditions are vital for preparing data for analysis.
- Visualization of data can be achieved using Matplotlib in conjunction with Pandas for better insights.
- The video emphasizes best practices for coding with Pandas, including the use of functions like `apply()` for applying custom operations to DataFrames.
- The course aims to equip viewers with the skills needed to start their first data analysis project using Pandas.
Questions Answered
What is Pandas and why is it important for data science?
Pandas is a crucial Python library for data science that allows for easy manipulation and analysis of data using data frames, which resemble Excel sheets and database tables. It is essential for tasks like querying, filtering, and preparing data for machine learning.
How can I export a DataFrame to a CSV file?
You can export a DataFrame to a CSV file using the `to_csv` method. After exporting, you can view the CSV file, which will display the data in a comma-separated format.
What are some basic plotting capabilities in Pandas?
Pandas provides basic plotting functions that allow for visualizations like line charts, bar charts, and histograms. You can visualize data distributions and trends using these plots.
How can I create new columns in a DataFrame using functions?
You can create new columns in a DataFrame by applying a function across rows. This can be done using a lambda expression to combine existing columns into a new summary column.
How can I filter rows in a DataFrame based on conditions?
You can filter rows in a DataFrame using conditions such as checking for specific values or ranges. The `query` method offers a more readable syntax for filtering.