<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vijay yadav on Medium]]></title>
        <description><![CDATA[Stories by Vijay yadav on Medium]]></description>
        <link>https://medium.com/@datasciencestuff?source=rss-7a227215482f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YnD-kJ9r8DUvtXyEF3ipfQ.jpeg</url>
            <title>Stories by Vijay yadav on Medium</title>
            <link>https://medium.com/@datasciencestuff?source=rss-7a227215482f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 18:26:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@datasciencestuff/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Complete guide to Pandas library (Python Code) — Part 4/ 4]]></title>
            <link>https://medium.com/analytics-vidhya/complete-guide-to-pandas-library-python-code-part-4-4-4e5855dd30e2?source=rss-7a227215482f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e5855dd30e2</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Vijay yadav]]></dc:creator>
            <pubDate>Fri, 06 Aug 2021 16:51:06 GMT</pubDate>
            <atom:updated>2021-08-16T05:01:46.918Z</atom:updated>
            <content:encoded><![CDATA[<h3>Complete guide to Pandas library (Python Code) — Part 4/ 4</h3><h4>Fundamental Statistics.</h4><p>Basically all the hard work we are going to put to understand about Statistics is just to make sense out of our data. As a part of data science projects, we have the responsibility to explore and draw meaning out of huge datasets in various situation and that is where different measures in statistics are used to understand distributions, variations within the data. Let’s explore this in detail.</p><h4><strong>Index</strong></h4><ol><li>Understanding Descriptive analysis</li><li>Measures in Descriptive analysis</li><li>Exploring python libraries for statistics</li><li>Visualization by using charts</li></ol><h3>What is Descriptive Statistics.</h3><p><a href="https://en.wikipedia.org/wiki/Descriptive_statistics">Source:</a> <em>A </em><strong><em>descriptive statistic</em></strong><em> is a summary statistic that quantitatively describes or summarizes features from a collection of information.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rbNtpsRwFIVCPNmj" /><figcaption>Photo by <a href="https://unsplash.com/@gtomassetti?utm_source=medium&amp;utm_medium=referral">Giorgio Tomassetti</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>So there are two categories to look when starting, descriptive and inferential statistics. Distinguishing factor between these methods are such that if you are in a situation to describe or visualize the whole dataset you can perform it using numbers or various charts like bar graph, histograms ,pie chart or line charts etc. You can also check for the shape of the whole dataset if it is symmetrical in nature or it is skewed. If it is skewed whether it is skewed to left or to right. All this important information falls under the category of descriptive statistics.</p><p>With inferential statistics you can work with a small sample of dataset to draw an inference for the whole population. In order to be sure about our assumptions for the whole population based on the inference of a sample, we use probability distribution which shows how much confidence we have in our assumptions. Eg. Analysis of Census data.</p><p>Commonly used methods to describe data in descriptive statistics are</p><ul><li><strong>measures of central tendency </strong>which uses<strong> </strong><em>mean, median and mode and</em></li><li><strong><em>m</em>easures of variability or dispersion </strong>which uses<strong> </strong><em>standard deviation (or variance), the minimum and maximum values of the variables, kurtosis and skewness.</em></li></ul><h3>Exploring python libraries for statistics</h3><p>Python comes with its own <a href="https://docs.python.org/3/library/statistics.html"><strong>statistics</strong></a> library in-built which is very practical to use in any given situation. However, after looking some basic functions in this library we will explore <strong>Pandas </strong>specifically in this article for our statistics need.</p><p>Let’s download a <a href="https://www.kaggle.com/zhaoyingzhu/heartcsv">dataset</a> to practice all these statistical functions and calculate values using above mentioned measures, and do it practically.</p><h4><strong>Measures of central tendency</strong></h4><p>A <strong>measure of central tendency </strong>is a single value that represents the center point of a dataset. This value can also be referred to as “the central location” of a dataset.</p><blockquote>mean(), median() , mode() ,</blockquote><p>Import necessary libraries and load the dataset.</p><pre>import pandas as pd<br>import statistics</pre><pre>data = pd.read_csv(&quot;heart.csv&quot; , sep= &#39;,&#39;)<br>data.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dYZ48gPPhVHlOJA6BgRF9A.png" /></figure><p>The most commonly used measure of central tendency is <strong>the mean</strong>. It is nothing but the average of the values and it’s only sensible to take a mean of a dataset when our data is fairly symmetrical in nature. If our dataset is skewed or has some heavy outliers (extreme values) then it is not the smartest choice to go with mean.</p><blockquote>What is the mean age of a person having heart disease?</blockquote><pre># using Statistics library, we can use mean()</pre><pre>statistics.mean(data[&#39;age&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vnlD6YuSIEng0aEHHHH0IA.png" /></figure><blockquote>What will be the middle value of our age column in the dataset?</blockquote><p>To answer this question we will use second measure called median() , this returns the middle value of the whole dataset , and this will be the best choice to go for if you dataset is skewed or have outliers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4lcC9eT0weEIzNwH0ApCfA.png" /></figure><blockquote>Which gender do we have more and what is the most occurring age in our dataset?</blockquote><p>Well , this type of question is very interesting to see and understand the distribution of the dataset itself, however <strong>mode() i</strong>s used mostly with categorical values as it returns the most frequently occurring value in the dataset. Suppose you want to see how is the data distributed gender wise , mode will be a good option to go with.</p><pre>data.age.value_counts().head(2)</pre><pre>data.sex.value_counts().head(2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IoebTIvNf5LwOWa1PEx8Ig.png" /></figure><p>As, you can see Statistics library is very helpful in getting these information if you don’t have access to any other libraries for any reason.</p><h4>Statistics using Pandas</h4><p>Now let’s see how this all values can be obtained using Pandas library.</p><p>In Pandas , there are several methods built on top of <a href="https://numpy.org/">numpy</a> library which makes it very simple to perform statistical analysis on both numerical as well as categorical values. Pandas commonly work with two type of data structure called as dataframe and series, on top to them you can apply every function directly.</p><blockquote>describe()</blockquote><p>By far, this is the most helpful function in pandas to view almost every important statistical value at a glance. This function by default gives the statistical summary for only <strong>numerical values.</strong> <br>For categorical, you can explicitly specify by (include = ‘ object’) parameter.</p><pre>#for numerical by default<br>data.describe()</pre><pre>#for categorical<br>data.describe(include = ‘object’)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3PWGEETXZZpBjtJX6q9LUQ.png" /></figure><p>The summary contains the following results:</p><ul><li><strong>Count :</strong> Total number of values in the column.</li><li><strong>Mean:</strong> The mean of each column</li><li><strong>std:</strong> The standard deviation</li><li><strong>min and </strong><strong>max:</strong> The minimum and maximum values</li><li><strong>25%, </strong><strong>50%, and </strong><strong>75%: </strong>The amount of values gathered under that much percentile</li></ul><p>Additionally, suppose you don’t wish to apply describe function to the whole dataset, you can also do it for specific column by using filter method.</p><pre>data[[&#39;age&#39; , &#39;sex&#39; , &#39;cp&#39;]].describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kt1I5HZdBG2r0KA0s_xhfA.png" /></figure><h3>Visualizing Data</h3><p>We have <strong>matplotlib</strong> and <strong>seaborn</strong> library in python for visualization purpose which is very widely used, and in this example we will be exploring seaborn mostly because its much simpler are aesthetically beautiful compared with matplotlib.</p><h4>Bar Charts</h4><p>Ideally used to display categorical labels or discrete numerical values with the frequency details using bars. Bar chart also allows to stack multiple bars next to each other or on top of each other for various categories in dataset.</p><pre>import seaborn as sns<br>import matplotlib.pyplot as plt<br>sns.set_theme(style=&quot;whitegrid&quot;)</pre><pre># Initialize the matplotlib figure<br>f, ax = plt.subplots(figsize=(8, 8))</pre><pre>sns.barplot(x=&quot;cp&quot;, y=&quot;age&quot;, data=data,<br>             color=&quot;b&quot;)<br>plt.title(&quot;Bar plot using SNS&quot;)<br>plt.xlabel(&quot;Chest Pain Value&quot;)<br>plt.ylabel(&quot;Age Range&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*E1l-thRUXz5wyJNrwKPH5g.png" /><figcaption>Image from Author</figcaption></figure><h4>Box Plot Chart</h4><pre># Initialize the matplotlib figure<br>f, ax = plt.subplots(figsize=(8, 8))</pre><pre>sns.boxplot(x=&quot;cp&quot;, y=&quot;age&quot;,<br>            hue=&quot;sex&quot;, palette=[&quot;m&quot;, &quot;g&quot;],<br>            data=data)<br>sns.despine(offset=10, trim=True)<br>plt.title(&quot;Box plot usiong SNS&quot;)<br>plt.xlabel(&quot;Chest Pain Value&quot;)<br>plt.ylabel(&quot;Age Range&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y9YIVkdgF5SiDLouf3Cgtw.png" /><figcaption>Image from Author</figcaption></figure><p>To Statistically understand and interpret boxplot, read below points.</p><ul><li>The line in the middle of the box is called median line.<br>It is more useful when your data is not normalized and prone to outliers.</li><li>Every Statistical detail in pandas.describe() method can be seen here, <br>the lower end of the box is 25% quartile, and the top part of the box is 75% quartile, and it simply means 75% of the datapoints are included within that range.</li><li>The top and bottom end you see, is the min and max values in dataset.</li><li>If the box is small in shape, it means our data is less variance or has smaller values</li><li>If the box is large, it means datapoints are fairly high in values and wide spread.</li><li>Position of the median line can tell if the majority of the data lies in the lower end or higher end or normally distributed if in middle.</li></ul><h4>Scatter Plot</h4><pre>import seaborn as sns<br>import matplotlib.pyplot as plt</pre><pre>f, ax = plt.subplots(figsize=(6.5, 6.5))<br>sns.despine(f, left=True, bottom=True)<br>sns.scatterplot(x=&quot;age&quot;, y=&quot;chol&quot;,<br>                hue=&quot;sex&quot;,<br>                sizes=(1, 8), linewidth=0,<br>                data=data, ax=ax )</pre><pre>plt.title(&quot;Scatter plot to show relationship&quot;)<br>plt.xlabel(&quot;age&quot;)<br>plt.ylabel(&quot;Cholestrol level Range&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*l8Ff3fE6YwHkT7ahceN8MA.png" /><figcaption>Image from Author</figcaption></figure><p>Scatter plot helps us very much to understand the relationships between two variables and get statistical values to prove them.<br>Here, we see that there is definitely some relationship between the two variable plotted Age and Cholesterol level.</p><p>At a glance, we can look and say that there is a positive relation which means as the age increase the cholesterol level of the people increases.</p><p><strong>Rel plot</strong></p><pre>sns.relplot(x=&quot;age&quot;, y=&quot;chol&quot;, size=&quot;cp&quot;, sizes=(15, 200), data=data);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*6_8qSgQcpgqtuHKt0ebRWw.png" /><figcaption>Image from Author</figcaption></figure><h4><strong>Heat map</strong></h4><p>This is probably the best graph to represent relationships, correlation within multiple variable at once. It’s specially helpful if you are working with a dataset with many numerical column and need to understand collinearity of variables for machine learning modeling.</p><p>Example and Dataset directly from from Seaborn package.</p><pre>import matplotlib.pyplot as plt<br>import seaborn as sns<br>sns.set_theme()</pre><pre># Load the example flights dataset and convert to long-form<br>flights_long = sns.load_dataset(&quot;flights&quot;)<br>flights = flights_long.pivot(&quot;month&quot;, &quot;year&quot;, &quot;passengers&quot;)</pre><pre># Draw a heatmap with the numeric values in each cell<br>f, ax = plt.subplots(figsize=(9, 6))<br>sns.heatmap(flights, annot=True, fmt=&quot;d&quot;, linewidths=.5, ax=ax)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jANgE0DBeLytiNkX1yQleg.png" /><figcaption>Image from Author</figcaption></figure><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5J4GtCL81wTcD6Yc" /><figcaption>Photo by <a href="https://unsplash.com/@shyshkina?utm_source=medium&amp;utm_medium=referral">Tetiana SHYSHKINA</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Although , Statistical analysis is very wide topic and methods to perform them depends on the type of datasets, I hope the above article and things we discussed can help a little in getting started.</p><p>I myself am further learning and exploring more about these methods ito get a deeper understanding and be better at statistical concepts.</p><p>I hope you enjoyed this 4 Part article series of Complete guide to pandas.<br>Read other ones after this, links to them attached below.</p><h3>Other articles.</h3><ul><li><a href="https://medium.com/analytics-vidhya/complete-guide-to-pandas-library-python-code-part-1-4-420cd5bd8249">Part 1 </a>, <a href="https://datasciencestuff.medium.com/complete-guide-to-pandas-library-python-code-part-2-4-4c0d9d9bd511">Part 2</a> and <a href="https://datasciencestuff.medium.com/complete-guide-to-pandas-library-python-code-part-3-4-6bc11f9465d0">Part 3</a> are linked here, do check it out incase if you haven’t already.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e5855dd30e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/complete-guide-to-pandas-library-python-code-part-4-4-4e5855dd30e2">Complete guide to Pandas library (Python Code) — Part 4/ 4</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete guide to Pandas library (Python Code) — Part 3/4]]></title>
            <link>https://medium.com/analytics-vidhya/complete-guide-to-pandas-library-python-code-part-3-4-6bc11f9465d0?source=rss-7a227215482f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bc11f9465d0</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[pandas-dataframe]]></category>
            <dc:creator><![CDATA[Vijay yadav]]></dc:creator>
            <pubDate>Mon, 19 Jul 2021 14:38:55 GMT</pubDate>
            <atom:updated>2021-07-26T05:44:01.962Z</atom:updated>
            <content:encoded><![CDATA[<h3>Complete guide to Pandas library (Python Code) — Part 3/4</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xQsZeoT-a1OKuW-x" /><figcaption>Photo by <a href="https://unsplash.com/@claybanks?utm_source=medium&amp;utm_medium=referral">Clay Banks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>Welcome to the visualization section of the Pandas series. Part 1 &amp; 2 covered the fundamentals of pandas library itself for getting started with your EDA journey and data wrangling steps using the most known techniques that the library has to offer.</p><p>No wonder that visualization part of any analysis is the most over-thought section, we might have the most interesting insight to share with people but its very easy to get confused while making the decision to choose the type of visualization pattern to make our message loud and clear. In this article we will explore couple of python based libraries that are most widely namely <a href="https://matplotlib.org/stable/"><strong>Matplotlib</strong></a> and <a href="http://seaborn.pydata.org/introduction.html"><strong>Seaborn</strong></a>.</p><p>Matplotlib has a module named pyplot which provides us with a MATLAB-like structure, which I am not sure what it means as I never used it personally and neither you will have to, so just imagine that it has a user-friendly interface where you have a lot of options to try out and build visuals with ease. <br>Later Seaborn was built on top of matplotlib library with more functionality and improved aesthetics.</p><h4>Index</h4><ul><li>Matplotlib</li><li>Seaborn</li><li>Exploring dataset to visualize numerical values</li><li>Exploring dataset to visualize Categorical values</li></ul><h3>Matplotlib</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lmBkWnpogvvz7PlK" /><figcaption>Photo by <a href="https://unsplash.com/@eskaylim?utm_source=medium&amp;utm_medium=referral">eskay lim</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, we will with an interesting <a href="https://www.kaggle.com/sidtwr/videogames-sales-dataset">dataset</a> and explore multiple visualization technique using matplotlib and seaborn.</p><p>Let’s start by reading our dataset into our jupyter notebook and do basic exploration.</p><pre>## Importing Essential Libraries</pre><pre>import pandas as pd<br>import numpy as np</pre><pre>import matplotlib.pyplot as plt<br>%matplotlib inline</pre><pre>import seaborn as sns</pre><pre>plt.rcParams[&#39;figure.figsize&#39;] = [20,10]</pre><pre>pd.options.display.max_rows = 1000<br>pd.options.display.max_columns = 1000</pre><h4>Load data</h4><pre>data = pd.read_csv(&quot;Video_Games_Sales_as_at_22_Dec_2016.csv&quot;)<br>data.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qoKPkBCBYR5drLo_13jXFw.png" /></figure><p>First method to visualize using pandas is using the plot method on its Series and DataFrame. It is basically a simple wrapper around <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.plot.html#matplotlib.axes.Axes.plot"><strong>plt.plot(</strong></a>).</p><pre>data.Name.value_counts().head(15).sort_values(ascending = True).plot(kind = &#39;barh&#39; , figsize = (10,10))</pre><pre>## <strong>barh</strong> is used for horizontal view, use <strong>bar</strong> for normal.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SComGelRHe-aSJmCIg9uvQ.png" /><figcaption>A simple Counts plot.</figcaption></figure><p>In above example, column <strong><em>Name</em></strong> is categorical type and to plot this data its necessary to have some quantifiable value around them like total number of observations in the column name. Here I am using value_counts() method to count total number of occurrences of each unique category in Name. Similarly it can be done for any categorical column, and note that bar plot is a common way to represent this type of data.</p><pre>data.groupby([&#39;Platform&#39; , &#39;Genre&#39;] , as_index=False)[[&#39;NA_Sales&#39;, &#39;EU_Sales&#39;]].sum().sort_values(by = [&#39;NA_Sales&#39; , &#39;EU_Sales&#39;], ascending = [0,0]).head(15).plot(kind = &#39;bar&#39;,xlabel = &quot;Country&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FauJVoFjC9zavlYDv4GvBQ.png" /><figcaption>Grouped barplot</figcaption></figure><p>If you read <a href="https://datasciencestuff.medium.com/complete-guide-to-pandas-library-python-code-part-2-4-4c0d9d9bd511"><em>article part 2</em></a> from this series, you will know exactly what this code is doing. Here we create a grouped bar plot of our resulting dataset created by grouping two columns <strong><em>platform</em></strong> and <strong><em>genre. </em></strong>Our quantifiable values around these categorical columns are sum of <strong><em>NA_sales</em></strong>, and <strong><em>EU_sales</em></strong>.<br>Parameter <em>as_index</em> is used to transform index values into column value for pandas dataframe so that it can be exported or simply used for plotting.</p><blockquote>Remember that the goal here is <strong>not</strong> to understand the information shown by this graph but to understand how to plot and when to plot such a graph, so if you have a hard time interpreting the results just move on and focus on attributes and parameters used.</blockquote><p>Now, instead of using <strong><em>plot()</em></strong> method inbuilt into pandas library, we can explicitly call this function from matplotlib.pyplot library and make more customised charts.</p><p>Let’s create a new feature by combining two existing columns to understand our next chart.</p><pre>df[&#39;NA_EU_sales&#39;] = (df[&#39;NA_Sales&#39;] + df[&#39;EU_Sales&#39;])<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*SaHJsFvmTrtNrpNtSQWXMw.png" /></figure><p>NA_EU_sales represents totals sales for NA and EU regions. We can use this quantifiable attribute to plot other categorical attributes against it.</p><blockquote><strong>Question</strong>: “ Plot Genre of the all games against overall sales in NA and EU combined”</blockquote><pre>plt.bar(x =&#39;Genre&#39; ,height=&#39;NA_EU_sales&#39; , data=df)<br>plt.ylabel(&quot;Total Sales&quot;)<br>plt.xlabel(&quot;Platform&quot;)<br>plt.title(&quot;Total Sales in NA and EU by Platform&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6r6NE1MHOuJ75CpC_ZzIIw.png" /></figure><h3>Seaborn</h3><p>Seaborn is used to create much better statistical graphs built on top of matplotlib library itself, using all its functionality plus many new features of its own. It also integrates closely with <a href="https://pandas.pydata.org/">pandas</a> data structures.</p><blockquote>Its plotting functions operate on data frames and arrays containing whole datasets and internally perform the necessary semantic mapping and statistical aggregation to produce informative plots. Its dataset-oriented, declarative API lets you focus on what the different elements of your plots mean, rather than on the details of how to draw them.</blockquote><h3>Distribution plots</h3><p>Distribution plots basically important to understand how the attributes in your datasets are distributed. Before plotting if you have below questions to answer then distribution plot is the way ahead.</p><ul><li>What range do the observations cover?</li><li>Is my data imbalanced, skewed or normally distributed.</li><li>Are there significant outliers in dataset ?</li></ul><h4>Plotting Univariate data</h4><p>Univariate basically means if you have only one column to visualize then following functions are best suited .</p><pre>sns.displot(data[&#39;User_Score&#39;] , kde = True , bins = 10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*5kiyDX7LrJWNHdqCb4JlGA.png" /></figure><p>displot() / histplot() are basically same plotting histograms across the x-axis to show the distribution of the data. In above chart we can see the highest score a user has is around 8 followed by 7, and it’s the best way to represent a chart for such quick insights. <br><br>Bins is an important parameter and must be set wisely depending upon your intuition of the output, otherwise a wrong bin value can change the representation of the whole chart , for example lets see the plot with bin=5.</p><pre>sns.displot(data[&#39;User_Score&#39;] , kde = True , bins = 5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*cnOSugWirABk19fOJwSM2g.png" /></figure><p>You can clearly see, that by reducing number of bins to 5, we are not clear of what this data represents. We might assume that the max values lies between 6–10 which will be misleading.</p><pre># loading new dataset withing seaborn package for better examples. </pre><pre>df_car = sns.load_dataset(&quot;car_crashes&quot;)<br>df_car.head()</pre><p><strong>Jointplot()</strong></p><pre>sns.jointplot(&#39;total&#39; ,&#39;alcohol&#39; , data = df_car , kind = &#39;reg&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*zrLlSBSGZ0fA-FJrk8Sqog.png" /></figure><p>By default, <a href="http://seaborn.pydata.org/generated/seaborn.jointplot.html#seaborn.jointplot"><strong>jointplot()</strong></a> represents the bivariate distribution using <a href="http://seaborn.pydata.org/generated/seaborn.scatterplot.html#seaborn.scatterplot"><strong>scatterplot()</strong></a> and the marginal distributions using <a href="http://seaborn.pydata.org/generated/seaborn.histplot.html#seaborn.histplot"><strong>histplot()</strong></a>:</p><p>here, if you set the type of plot by <strong><em>kind = “ reg” , </em></strong>it draws a regression line across your datapoint and better displays the relationship within.</p><p><strong>Pairplot()</strong></p><p>The <a href="http://seaborn.pydata.org/generated/seaborn.pairplot.html#seaborn.pairplot"><strong>pairplot()</strong></a> function is the best to draw relationship within every attribute in your dataset , it offers a similar blend of joint and marginal distributions. <br>Rather than focusing on a single relationship, however, <a href="http://seaborn.pydata.org/generated/seaborn.pairplot.html#seaborn.pairplot"><strong>pairplot()</strong></a> uses a “small-multiple” approach to visualize the univariate distribution of all variables in a dataset along with all of their pairwise relationships:</p><pre>sns.pairplot(df_car)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RtK8fBlt4suX4A9BU43ing.png" /></figure><p>Using this plot you can easily see, which attributes have positive , negative or neutral relationships. This is also useful to understand multi-collinearity among attributes.</p><h3>Categorical Plots</h3><p>Alright, so now you know what to use for numerical based data and visualize the distribution, but what works best when you have categorical values. They are naturally different than numerical values, hence seaborn has some dedicated functions to handle them best.</p><p><strong>barplot()</strong></p><pre>sns.barplot(x = &#39;Genre&#39; , y = &#39;NA_EU_sales&#39; , data=df , estimator= np.std)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rk2eW9gYBUSYwMquDT3aLw.png" /></figure><p>In seaborn, the <a href="http://seaborn.pydata.org/generated/seaborn.barplot.html#seaborn.barplot"><strong>barplot()</strong></a> function operates on a full dataset and applies a function to obtain the estimate (taking the mean by default). The parameter <em>estimator = “ np.std”</em> is basically calculating standard deviation, and you can use various out metrics namely mean, min , max etc.</p><p><strong>Scatterplot()</strong></p><pre>sns.scatterplot(x = &#39;User_Count&#39; , y = &#39;User_Score&#39; , data=data)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xb4xi9H1U3f4oGa79uc4Vg.png" /></figure><p>Scatter plots are very useful in drawing relationships within multiple attributes easily, it shows the distribution of all data points in 2D space and makes it very clear of where most of the data lies.</p><p><strong>boxplot()</strong></p><p>Let’s say you dataset size is increasing and you might have tremendous variety of values which you are not sure how to bin. Understanding the size of data according to the quartile ranges is very useful ti identify outliers within the dataset, and thats where boxplots shines most.</p><pre>sns.boxplot(data= df.drop([&#39;Year_of_Release&#39; , &#39;Genre&#39;], axis=1).head(50) , orient= &#39;h&#39; ,palette=&quot;Set1&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jextxRJ-vKG0kMgEKI1v2w.png" /></figure><blockquote>This kind of plot shows the three quartile values of the distribution along with extreme values. The “whiskers” extend to points that lie within 1.5 IQRs of the lower and upper quartile, and then observations that fall outside this range are displayed independently. This means that each value in the boxplot corresponds to an actual observation in the data.</blockquote><p><strong>Heatmap()</strong></p><pre>df_car_corr = df_car.corr()<br>df_car_corr.head()</pre><pre>sns.heatmap(df_car_corr , annot= True , cmap = &quot;Blues&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EZ72yV3MjaxkFTZeluRYpA.png" /></figure><p>To find correlations within all the attributes, <em>heatmap()</em> is best representational plot, displaying strong to least related variables.<br>This is very important in machine learning process where you need to understand how well variables are related to each other. To interpret this chart remember that the darker the shade of a box, stronger the relationship is . <br><em>For example, we see that total and no_previous are very highly related, followed b no_distracted, alcohol etc.</em></p><h3>Conclusion.</h3><ul><li>So to conclude, always remember that these quick ways of plotting charts using matplotlib and seaborn libraries are the best way to visualize your findings from EDA and transform informations into graphs and dashboards.</li><li>Also, these are only few of the options specified here because covering everything is just not possible because there are so many also thats why there are dedicated documentation pages of each libraries.</li><li>Part 4 of this series will sum up of these knowledge and I will share some information regarding <strong>statistical modeling</strong> using pandas.</li></ul><h4>Other articles.</h4><ul><li><a href="https://datasciencestuff.medium.com/complete-guide-to-pandas-library-python-code-part-1-4-420cd5bd8249">Part 1</a> and <a href="https://datasciencestuff.medium.com/complete-guide-to-pandas-library-python-code-part-2-4-4c0d9d9bd511">Part 2</a> are linked here, do check it out incase if you haven’t already.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bc11f9465d0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/complete-guide-to-pandas-library-python-code-part-3-4-6bc11f9465d0">Complete guide to Pandas library (Python Code) — Part 3/4</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete guide to Pandas library (Python Code) — Part 2/ 4]]></title>
            <link>https://medium.com/analytics-vidhya/complete-guide-to-pandas-library-python-code-part-2-4-4c0d9d9bd511?source=rss-7a227215482f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c0d9d9bd511</guid>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Vijay yadav]]></dc:creator>
            <pubDate>Sun, 18 Jul 2021 12:41:23 GMT</pubDate>
            <atom:updated>2021-07-26T05:33:41.411Z</atom:updated>
            <content:encoded><![CDATA[<h3>Complete guide to Pandas library (Python Code) — Part 2/ 4</h3><p>We learnt a lot of fundamentals in part one. Now you know how to make subsets of data-frame using multiple conditions, filters and selections.<br>We also covered how to handle missing values, identifying reasons behind the missing values and summarized datasets using multiple Pandas function.</p><p>This part will focus on <strong>Data Wrangling capabilities</strong> of <a href="https://pandas.pydata.org/pandas-docs/stable/index.html">Pandas</a> library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*84TDQCD1j0AGVdlH" /><figcaption>Photo by <a href="https://unsplash.com/@firmbee?utm_source=medium&amp;utm_medium=referral">Firmbee.com</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Index</h4><ul><li>Work with different data types.</li><li>Reshaping DataFrame objects</li><li>Pivoting</li><li>Data aggregation and GroupBy operations</li></ul><p>For the next two articles, we will be using <strong>Stack overflow survey for 2020 dataset.</strong> This dataset has nearly 65,000 responses from over 180 countries. The foal of survey is to cover all aspects of the developer experience from career satisfaction and job search to education and opinions on open source software.</p><p>Dataset : <a href="https://insights.stackoverflow.com/survey">https://insights.stackoverflow.com/survey</a></p><h4>Load Dataset, and basic data understanding.</h4><pre>data = pd.read_csv(&quot;survey_results_public.csv&quot;)<br>data.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GWM4ZXXMrE-8LHDjINqYKQ.png" /><figcaption><em>First Glance of the Dataset</em></figcaption></figure><p>Always keep the first goal of your EDA process to understand and verify authenticity of all the attributes in your dataset. <br>Before starting anything check for few basic things mentioned below,</p><blockquote><strong>Considering Dataset = df</strong></blockquote><pre><strong>df.shape</strong>  #Shape of the whole dataset</pre><pre><strong>df.dtypes</strong>  #Data type of every attribute</pre><pre><strong>df.describe</strong>  #Overview of all statistical detail of Numerical col.</pre><pre><strong>df.describe(include = &#39;object&#39;)</strong>  #For Object Columns.</pre><pre><strong>df.isnull().sum()  </strong>#Total number of null values in Dataset.</pre><pre><strong>df[&#39;column name&#39;].unique()</strong>  #Total number of unique cat. values</pre><h4><em>Work with different data types</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gjAyhxZIPiPIE3NS" /><figcaption>Photo by <a href="https://unsplash.com/@deonblack?utm_source=medium&amp;utm_medium=referral">Deon Black</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Performing above steps you will get a good overview of your dataset, and let’s say you find various attributes that are suppose to be object or categorical format are in integer format or vice versa, also what if a column that is suppose to be in a date format is in object format. We need to fix this before going ahead with our analysis as this is a very important step to make sure our dataset is telling the correct story.</p><pre><strong># Converting numeric datatype to Object</strong></pre><pre>data[&#39;Respondent&#39;] = data[&#39;Respondent&#39;].astype(&#39;object&#39;)</pre><pre><strong># Converting object datatype to Numeric</strong></pre><pre>data[&#39;Age&#39;] = pd.to_numeric(data.Age)</pre><pre><strong># Converting object datatype to Date format</strong></pre><pre>new_data[&#39;date&#39;]  = pd.to_datetime(new_data[&#39;date&#39;])</pre><h4>Reshaping and Pivot tables</h4><p>Now, reshaping dataset simply means making and breaking the dataset in a format that suits most to your requirement. For example, if you want to create time series plot, you need a <strong>date</strong> column as your index and the value that needs to be plotted has to be in columns against each date.</p><p>For such a requirement you don’t even need rest of the columns in dataset to work with, so you can either drop them or simply create a separate dataset with specific columns required.</p><p>Now, to reshape the dataset you can use multiple functions in pandas namely <strong><em>pivot() , pivot_table () , melt() , stack() , unstack()</em></strong><em> </em>based on the manipulations you want to perform.</p><p>Let’s see this in action, and for this we will use a separate <a href="https://www.kaggle.com/rashikrahmanpritom/heart-attack-analysis-prediction-dataset">dataset</a>. just for more convenience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mbX8YaHBkIriIvI3TDxT-A.png" /></figure><p>Now, as you can see this dataset has more numerical columns but no date attribute. So, we can create one just for demonstration purposes</p><pre>new_data[&#39;date&#39;] = pd.date_range(start=&#39;2020/01/01&#39;  , end=&#39;2020/10/29&#39;, freq=&#39;D&#39;)</pre><pre><br># pd.daterange() -- This function creates a date range.</pre><pre># start -- This specifies the start of the date range</pre><pre># end  -- This specifies the end of the date range.</pre><pre># freq -- Creates dates based on days. Other options are W, M, Y.</pre><pre># period -- Specifies how many interval between dates(12 for a Year)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ZoOMPwaoVSnoll8yzht6w.png" /></figure><h4>Creating a Pivot</h4><pre>new_data.pivot(index=&#39;date&#39; , columns=&#39;cp&#39; ,values = &#39;age&#39; ).head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0q8CeZcB7T8asK9tIKv-wg.png" /></figure><p>While you create a pivot <strong>index</strong> , <strong>column</strong> and <strong>values</strong> are three important parameters which need to be specified and the data will be re-shaped accordingly. Note that the values parameter is the one which will be plotted against these row indexes and column indexes.</p><p><strong>Important : </strong>Remember if the values parameter is omitted and there are multiple columns in the dataset , resulting pivoted dataframe will take all those columns and create an hierarchical index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l7dgo1ao6HJh48XH_UYxfw.png" /></figure><p>If you see, in this example I did not provide a values parameter, hence the pivot created a multi-index dataframe with all the other columns in dataset.</p><p>There are so many NaN values in above dataset, and we can fill them using fillna() argument with any values.</p><pre>new_data.pivot(index=&#39;date&#39; , columns=&#39;cp&#39; ,values = [&#39;age&#39;,&#39;sex&#39; ,&#39;chol&#39;]).fillna(0).head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tVLw8pMXpvx9uLTn0pCRDA.png" /></figure><blockquote><a href="https://pandas.pydata.org/docs/reference/api/pandas.pivot.html#pandas.pivot"><strong>pivot()</strong></a> will throw an error of ValueError: Index contains duplicate entries, cannot reshape if the index/column pair is not unique. In this case, consider using <a href="https://pandas.pydata.org/docs/reference/api/pandas.pivot_table.html#pandas.pivot_table"><strong>pivot_table()</strong></a> which is a generalization of pivot that can handle duplicate values for one index/column pair.</blockquote><pre>new_data.pivot_table(index = &#39;age&#39; , columns= &#39;sex&#39; , values = [&#39;chol&#39; , &#39;thall&#39;,&#39;oldpeak&#39;] ).head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*_O499XEVPssaf8DEWRhKHg.png" /></figure><h4>Melt( )</h4><p>melt() is another function that can be used to reshape the dataset in similar way, and it takes following parameters.</p><pre>new_data[[&#39;age&#39; , &#39;sex&#39; , &#39;cp&#39;]].melt(id_vars= [&#39;age&#39; , &#39;sex&#39;] , var_name=&#39;Rest of the column&#39;).head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6KzBduCUzQjgzTbFfGYYgw.png" /></figure><p><strong>Important: </strong>In melt() , id_vars is the parameter which will be treated as index values for reshaping , same as index and columns in pivot() and value_vars is same as the value parameter.</p><p>However, in melt if you do not provide the value_vars parameter it will create the stack vertically with every column in the dataset. <em>(try to plot it once)</em></p><h4>Data aggregation and GroupBy operations</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*farc_0AAKXisgFTy" /><figcaption>Photo by <a href="https://unsplash.com/@iamchang?utm_source=medium&amp;utm_medium=referral">Chang Duong</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This section of the article is the most interesting part, and there is absolutely no limit of how many things that can be done using groupby() and agg() functions, specially by combining them together.</p><pre>new_data.groupby([&quot;sex&quot; , &quot;cp&quot;]).count()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7hYy-M4BP51VAxgyFwu5bA.png" /></figure><p>Here, we used groupby() function to group the large amount of data and now we can apply various functions on the whole group of data. <br>groupby() operation involves some combination of splitting the object, applying a function, and combining the results. Output is a groupby object that contains information about the groups.</p><p>Functions like max(), min(), mean(), first(), last() can be quickly applied to the GroupBy object</p><pre>new_data.groupby([&quot;sex&quot; , &quot;cp&quot;]).max()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pcBYPwW4mqI257zslO3reA.png" /></figure><p>What you see here as an output is basically the maximum value of each attribute when grouped by sex and age column, this can be interpreted as</p><ul><li>“<em>the maximum age of a female (sex = 0) having low chest pain (cp = 0) is 71</em> ”</li><li>“<em>the maximum age of a female (sex = 0) having high chest pain (cp = 3) is 69</em>”</li></ul><p>Similarly you can use rest of the functions and get these meaningful insights so quickly.</p><p>You can choose how many columns you want to show in the output by using filters after the groupby clause, let’s only select <em>age</em> and <em>chol </em>columns to display their maximum values.<br>This is useful, incase you want to see the maximum values but only for specific columns and not all of them.</p><pre> new_data.groupby([&quot;sex&quot; , &quot;cp&quot;])[[&#39;age&#39; , &#39;chol&#39;]].mean()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*eW41Mor4IxYsPOTRF1S13w.png" /></figure><p>Suppose you want to find all these values for only female patients, or only people with high chest pain value of 3 to maybe prioritize their medication , you can do so by filtering a column to apply groupby functions on special group only and not the whole dataset</p><pre>new_data[new_data[&#39;cp&#39;] == 3].groupby([&#39;sex&#39; , &#39;thall&#39;]).max()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YKE4UGUlAs_jsmOg4C4zpg.png" /></figure><pre>new_data[new_data[&#39;sex&#39;] == 0].groupby([&#39;sex&#39; , &#39;thall&#39;]).max()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rjgDXB6OBy4H6qoiaCi8oQ.png" /></figure><p>Also, incase you don’t want to keep these columns used for groupby as index, and want to treat them like a column in dataframe, or lets say you are done with manipulating the datasets using groupby functions and now you want to export them as a final dataset, you can do so by passing an additional parameter as_index = False and they will no longer be index values but a column in the dataframe. Very cool…isn’t it?</p><pre>new_data[new_data[&#39;cp&#39;] == 3].groupby([&#39;sex&#39; , &#39;thall&#39;] , as_index = False).max()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lCfkbmO1xQpl_JBih5aw5w.png" /></figure><p>These are only few ways in which you can use groupby, and I cant emphasize enough that how powerful this function is for all purpose analysis.</p><p>Now , let’s talk about aggregation function which is just as amazing as groupby, and if we combine them its more powerful.<br>Aggregation function , agg() is used to aggregate functions for multiple computations tasks at once. You can also pass a list of functions to be applied on a particular column and it can calculate all the respective values returning a multi-level index dataframe.</p><pre>new_data.groupby([&#39;sex&#39; , &#39;cp&#39;]).agg(max)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fBo6nFQgDOYgmZ08eJG79Q.png" /></figure><p>This is the simplest way to use agg() and pass a function to carry out some operation , it will pass that function through every column and output the computed values in dataframe. But wait, isn’t the same thing done by just specifying max() function directly like in the last example, then why do we need agg() function.</p><p>This is where the agg() function really shines and shows us its true power, where you can use (key : value) pair to carry out different operations throughout the dataset at once. In this function key : value actually refers to (column : Function ) accordingly,</p><pre>new_data.groupby([&#39;sex&#39;, &#39;cp&#39;]).agg({&#39;age&#39;: max , &#39;trtbps&#39; : np.mean})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*RJ1lZsqGYT8w9pj_aaRhsQ.png" /></figure><p>In above example, as you can see we were able to compute two different values for two different columns at the same time and you can imagine how powerful this is in terms of generating insights. agg() function takes a dict or list of key value pair to operate on grouped values.</p><p>You can literally create your own dict or list with mappings of different functions to different columns and simply pass them to the agg() functions and it will return you the dataframe with all the computed values.</p><pre>agg_fucntion = {&#39;age&#39;: [max , min , sum] , &#39;trtbps&#39; : min}</pre><pre>new_data.groupby([&#39;sex&#39;, &#39;cp&#39;]).agg(agg_fucntion)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*7MsNItkiGnwDrXpMlcbX0g.png" /></figure><p>As you can see, I passed a list of functions to be applied on the column <em>age</em>, and one function to be applied on <em>trtbps</em> . Resulting dataframe outputs the values as expected and the fact that this can be used in so many analysis situations and carry out complicated logics with so much ease, is exciting.</p><h4>Conclusion.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JqUehXPRIL-uDGpP" /><figcaption>Photo by <a href="https://unsplash.com/@alschim?utm_source=medium&amp;utm_medium=referral">Alexander Schimmeck</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>So yea , there you go with all about the most used feature and functions for data wrangling using Pandas in Python which you will definitely have to use in your EDA process.</p><ul><li>We covered about working with different datatypes , and how to handle them or change their datatype as required.</li><li>Reshaping the dataset using melt() and pivot() functions. Understanding how pivot and pivot_table can be used in different situations.</li><li>We looked into how to use groupby() and agg() functions in best way possible and how to make most of these functions available at our disposal.</li><li>There is ofcourse a lot more to do with them, but if you get the concept and idea about how to use it and how does the function works initially, then you can use it in numerous ways.</li></ul><p>Next article in this series is <strong><em>Plotting and Visualization </em></strong>using Pandas.</p><h4>Other articles.</h4><ul><li><a href="https://datasciencestuff.medium.com/complete-guide-to-pandas-library-python-code-part-1-4-420cd5bd8249">Part 1</a> and <a href="https://datasciencestuff.medium.com/complete-guide-to-pandas-library-python-code-part-3-4-6bc11f9465d0">Part 3</a> are linked here, do check it out incase if you haven’t already.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c0d9d9bd511" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/complete-guide-to-pandas-library-python-code-part-2-4-4c0d9d9bd511">Complete guide to Pandas library (Python Code) — Part 2/ 4</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete guide to Pandas library (Python Code) — Part 1 / 4]]></title>
            <link>https://medium.com/analytics-vidhya/complete-guide-to-pandas-library-python-code-part-1-4-420cd5bd8249?source=rss-7a227215482f------2</link>
            <guid isPermaLink="false">https://medium.com/p/420cd5bd8249</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[analysis]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Vijay yadav]]></dc:creator>
            <pubDate>Sun, 11 Jul 2021 11:17:16 GMT</pubDate>
            <atom:updated>2021-07-24T07:57:51.634Z</atom:updated>
            <content:encoded><![CDATA[<h3>Complete guide to Pandas library (Python Code) — Part 1 / 4</h3><p>Out of many things I personally implemented throughout my career as Data scientist, today in this article I am going to focus on one Python library that has really helped me to sail through all difficult analysis situations, all basic to advanced data manipulations and Explorations techniques using Pandas library.</p><p>Pandas library is as powerful as you might expect it to be. Take it in this way that no matter which type of project you start on , you will start its exploration using pandas.</p><h4>Index</h4><ol><li>Importing Data</li><li>Indexing , Subsetting , Selection</li><li>Data Type Conversions (Date / Timestamps)</li><li>Working with Missing data</li><li>Data Summarization</li></ol><p>For this Example we will be using a dataset about heart disease , get the data <a href="https://www.kaggle.com/rashikrahmanpritom/heart-attack-analysis-prediction-dataset">here</a> .</p><pre><em>## Import Essential Libraries</em></pre><pre>import pandas as pd<br>import numpy as np</pre><pre><em>## To let pandas display max columns , rows</em></pre><pre>pd.options.display.max_rows = 500<br>pd.options.display.max_columns = 500</pre><h4>Importing Data</h4><p>Pandas has several ways of importing a dataset depending on the type of the file format.</p><ul><li>CSV format (<em>Note: Keep the data file in the same directory as the jupyter notebook , else use the complete path)</em></li></ul><pre>df = pd.read_csv(&quot;heart.csv&quot;)</pre><ul><li>Excel Format</li></ul><pre>df = pd.read_excel(&quot;heart.xlsx&quot;  , sheet_name = &#39;&#39;)</pre><p>These are nothing but couple of tool that pandas has for you to use as reader function to read the data into pandas. Similarly, in-case if you want to export the dataset by the end of you EDA process, you can use their writer functions as <em>pd.to_csv()</em> and pd.<em>to_excel().</em></p><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cejv-KW3EdhpIx2lUGdNZA.png" /><figcaption>Image by <a href="https://medium.com/u/7a227215482f">Vijay yadav</a></figcaption></figure><p>A quick glance of the data set is always a better place to begin with, you can view first few rows by using its head method, similarly if you need to view last rows of the dataset you can do so by .tail() method.</p><pre>df.tail()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-TN00TPRy7pyEPsGXg3WLA.png" /><figcaption>Image by <a href="https://medium.com/u/7a227215482f">Vijay yadav</a></figcaption></figure><h4>Indexing , Subsetting , Selection</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7JqOE6KiEvE5xG8-" /><figcaption>Photo by <a href="https://unsplash.com/@mbaumi?utm_source=medium&amp;utm_medium=referral">Mika Baumeister</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Just remember the filter function while using an excel sheet, how you can simply select and work on a subset of data, how you can select any particular data from the whole dataset and almost do any operation on it. Thats exactly how the Python indexing operator ‘ [ ] ’ and attribute operator ‘ . ’ work in pandas.</p><p>Basically we will be using label based indexing <strong>.loc , </strong>and<strong> </strong>integer based indexing<strong> .iloc</strong> for multi-axis indexing. Understand this carefully, it’s tricky but very important.</p><pre>df.loc[:]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ny9eZd_1JMR80SfQRwfDdg.png" /><figcaption>Image by <a href="https://medium.com/u/7a227215482f">Vijay yadav</a></figcaption></figure><blockquote><strong>LOC (row indexer , column indexer)</strong></blockquote><p><em>loc</em> method takes two inputs, first one is called row indexers which will take index label as values, second parameter is called column indexer which takes the column label as identifiers to select data and the sign ‘ : ’ shows the range of value to be subsetted.<br>Suppose you don’t provide any value but ‘:’ sign as in the above example, loc method by defaults then shows every label of the dataset.</p><pre>df.loc[0:5]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EL-qP8vzyuIS9cjjMmpFXA.png" /></figure><p>In this example , we have mentioned the loc method to select from index label 0 to 5, and since no column labels are specified it will select all of them by default.</p><pre>df.loc[0:10,&#39;age&#39;]</pre><figure><img alt="Output showing only one column as we mentioned only one label  “age” in the column indexer" src="https://cdn-images-1.medium.com/max/372/1*rf4B0uKxh7glvBPBQw5y0w.png" /></figure><p>In this example, we have mentioned only one column indexer label “age” and hence the output subsets the data row wise as per the row indexer, and column wise as per the column indexer.</p><p>Further, we can slice the data from any range randomly specifying its label in range.</p><pre>df.loc[50:60 , [&#39;age&#39; , &#39;sex&#39;, &#39;cp&#39;]]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*tcEolPtMeIh2NXoCmgwVFA.png" /></figure><p>Here is an interesting result, as you may notice that we have specified the row_indexer from range 50:60 , and in the column indexer we have passed a list of column indexer.</p><p>Thus, you can imagine how powerful this tool is in case of slicing dataset based on label.</p><ul><li>A single label, e.g. 5 or &#39;a&#39;</li><li>A list or array of labels [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]</li><li>A slice object with labels &#39;a&#39;:&#39;f&#39;</li></ul><blockquote><strong>.iloc Integer based indexing</strong></blockquote><p>Integer based indexing simply means locating any specific row or column by integer index (from 0 to length-1 of the axis). In this label don’t matter and thats why this approach maybe more robust method of selecting the subset because it wont be affected even if the column names are changed throughout the program.</p><pre>df.iloc[50:55 , [ 0,6,10]]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*vDKTF5TgClxTkDBR2p9Y4w.png" /></figure><p>As you can see, we have used row indexes from 50:55 to subset row , and column indexes by specifying their respective indexes.</p><h4>Using isin() function for selection</h4><pre># Create a new column <br>old_age = list(range(60,100))</pre><pre># First Method<br>df[df[&#39;age&#39;] &gt; 60]</pre><pre># Second Method<br>df[&#39;senior_citizens&#39;]  = df[&#39;age&#39;].isin(old_age)</pre><pre>df[df[&#39;senior_citizens&#39;] == True ].head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eswm_7OjdIQu-bs1WTUu5A.png" /><figcaption>Image by <a href="https://medium.com/u/7a227215482f">Vijay yadav</a></figcaption></figure><p>We randomly created an extra feature called ‘Senior Citizens’ , by labeling everyone who is above age 60. In this example we can see two ways of creating a subset of data. First method uses a simple greater than operator to compare the numerical value and thus we end up with the correct set of data.</p><p>However, this approach will not be useful if we have had categorical value or a condition that requires to compare multiple values.<br>That’s where we use <strong>isin() </strong>function, which allows us to iterate over every value provided in a list or array format. In this approach we never need to bother about our code even if the value or range of the original variable “old age” changes. Since we are using isin() function it will hold true as long as the variable exists.</p><pre>## Also you can index data by using the index of the data</pre><pre>df[df.index &gt; 10]</pre><pre>df[df.index.isin([2,5,7,8,4,5,7,8,7,5,4,3,5,7,8,84])]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uWAXAEgiigf6FWjOfwIVnQ.png" /></figure><h4>Data Type Conversions (Date / Timestamps)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3Z2kP3LXnrHTQSay" /><figcaption>Photo by <a href="https://unsplash.com/@waldemarbrandt67w?utm_source=medium&amp;utm_medium=referral">Waldemar Brandt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Pandas is very flexible in handing various data types within a DataFrame. Thus it also provides great feasibility to convert any given data type of a series to other valid dtypes.<br>For example, it’s possible that when you import your data from excel to jupyter notebook for EDA, the date column might be converted into a string format which is practically un-useable without converting it back to date format.</p><p>Let’s create a sample dataframe to demonstrate this situation.</p><pre>import datetime</pre><pre>date = pd.date_range(&#39;2020/01/01&#39;, end = &#39;2020/12/31&#39; , freq= &#39;D&#39;)</pre><pre>df_date = pd.DataFrame(date , columns = {&#39;Date&#39;})<br>df_date.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*c5fpqBoZIoeteoPVyFe-9Q.png" /></figure><p>This function in pandas create a range of date as per the provided attributes like specified start date, end date, frequency can be day, week , month and year.</p><p>Default dypte of date column<br>is datetime.Datetimeindex, and we can convert that to object and vice versa just for demo.</p><pre>df_date[&#39;Date&#39;] = df_date[&#39;Date&#39;].astype(&#39;object&#39;)</pre><pre>df_date[&#39;Date&#39;] = df_date[&#39;Date&#39;].apply(pd.to_datetime)</pre><p>Above function converts the datetype to Object , and back to datetime format. Similarly you can use this method to convert as many columns required, or provide a pre-check for the columns that you wish to parse as date.</p><pre>df_date[&#39;Day Name&#39;]  = date.day_name()</pre><pre>df_date[&#39;Month_Number&#39;] = date.month</pre><pre>df_date[&#39;Month_Name&#39;] = date.month_name()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*ovd3pAwAmd61OZT-qjxztA.png" /></figure><p>As you can see in the above code, we can generate multiple extra features which could be very important for further analysis, understanding the data overall or just for the sake of self exploration. However, this function in pandas is really handy when you have to work with date time format.</p><h4>Working with Missing data</h4><blockquote>“As data comes in many shapes and forms, <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/missing_data.html">pandas</a> aims to be flexible with regard to handling missing data. While NaN is the default missing value marker for reasons of computational speed and convenience, we need to be able to easily detect this value with data of different types: floating point, integer, boolean, and general object.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CaERCcjbyBmmI8kC" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=medium&amp;utm_medium=referral">Brett Jordan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Handing missing data is one of the most important and in-fact a go-to step in any pre-processing approach. Missing values are just like those missing legos which can make or break your whole dataset. Identifying missing data, finding the reason behind that missing data, and selecting an appropriate method to impute data is a very time and energy consuming task , so let’s understand some of them.</p><pre># First lets check if we have any null value in data</pre><pre>print(&quot;There are total {} null values&quot;.format(df.isnull().any().sum()))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u-WCtlQAUyAgDT4x9FQHLg.png" /></figure><p>Since we don’t have any null values in our dataset, let’s create some null values. We can simply select certain rows using loc or iloc functions as we discussed earlier in this article and then assign then np.nan values.</p><pre># assign null values to age and sex column.</pre><pre>df.loc[50:70, [&#39;age&#39; , &#39;sex&#39;]] = np.nan</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PHv0AsA8WVXMpm0PamiYdw.png" /></figure><pre># now lets check again for any null value in data</pre><pre>print(&quot;There are total {} null values&quot;.format(df.isnull().any().sum()))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2nmSgPN-nDfaMxfsbe-ZVg.png" /></figure><p>Now, we have successfully assigned value np.nan to two columns here namely “age” and “sex” , and we can verify it again by calling isnull() function again.</p><p>Imputing data to a missing column is something which needs to be given some good thought before proceeding. Really just ask yourself these questions before starting to imputing values.</p><ul><li><em>Why is the data missing at the first place, is it missing because of some actual reason, unavailability of data, or was it in-applicable data.</em></li><li><em>How much data is missing anyways, how does it represents the whole data.</em></li><li><em>Is my missing column. containing numerical or categorical data.</em></li><li><em>Does missing of the data has some pattern.</em></li></ul><p>So, as you see these are few questions which you may try to answer before jumping into the while data imputation process.</p><pre>#First Method<br>df.loc[50:70, [&#39;age&#39;]] = 0</pre><pre>#Second Method<br>df[&#39;sex&#39;] = df.loc[50:70, [&#39;sex&#39;]].fillna(df[&#39;sex&#39;].mode()[0])</pre><pre>#Third Method<br>df[&#39;age&#39;] = df.loc[50:70, [&#39;age&#39;]].fillna(df[&#39;age&#39;].mean())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Rv-53oB2jamLeBAk76E4A.png" /><figcaption>Image by <a href="https://medium.com/u/7a227215482f">Vijay yadav</a></figcaption></figure><p>First method is simply an assignment method, you can simply assign any random value to the column if it doesn’t have any meaning , or let’s say you are not sure what value to put so you just assign everyone a value of “ 0 ” .</p><p>But let’s say your missing column is a categorical value and you can obviously not generate any new values by any statistical or aggregate approach. In such case you can look which value appears most in the data, and you can take the mode of the column and just impute that value by accessing the first value.<br>Ofcourse, this is not the best way to impute but as I said earlier it depends on the answer to above questions in your case.</p><p>Similarly , in third case we have <strong>fillna()</strong> function of Pandas which easily handles missing values. Using fillna(), missing values can be replaced by a special value or an aggregate value such as mean, median. Furthermore, missing values can be replaced with the value before or after it using forward fill method and backward fill method which is pretty useful for time-series datasets.</p><h4>Drop the Missing values</h4><ul><li><em>When should you consider to drop any value from the dataset ?</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7puE_LbpJEd5V1hU" /><figcaption>Photo by <a href="https://unsplash.com/@cccintyaaa?utm_source=medium&amp;utm_medium=referral">Cintya Marisa</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Simple enough, let’s say you have 1000 rows of data and you have only 10 or at the max 100 rows of empty values, thats like maximum of 10% data. Deleting these many records might not affect your overall dataset quality or any underlying information (mostly) , however it can definitely make your dataset much cleaner in terms of missing value records. Remember it as a tradeoff, is it worth it or not will depend on the dataset itself or the specific situation.</p><pre>df.dropna(axis=0, inplace=True)</pre><pre>print(&quot;There are total {} null values&quot;.format(df.isnull().any().sum()))</pre><pre>print(&quot;Updated Shape of the dataset is {}&quot;.format(df.shape))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G4Dw2JMqYNtms-FqTvz2_w.png" /></figure><p>Note how we have total “ 0 ” null values now, but our total shape of the dataset is reduced from 303 rows to 282 rows. This means we have successfully dropped all the rows which had NaN or missing values thus making our dataset free of missing values. Also we use (<strong>axis = 0)</strong> because we intend to drop missing values across rows.</p><p>When we use <strong>“inplace”</strong> attribute with value as true , the function drops those rows from the original dataset and thus it is a permanent change that you make to the original dataset and it cannot be reverted. Solution for that is either you create a copy of dataset before dropping, or simply create a another instance of your dataset while dropping.</p><pre>upated_dataset = df.dropna(axis=0) ## assigning new instance of Data</pre><pre>print(&quot;There are total {} null values in the Updated dataset&quot;.format(df.isnull().any().sum()))<br>print(&quot;Updated Shape of the new dataset is {}&quot;.format(df.shape))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HOHlZEbl4ZYwhV-JYCzh1w.png" /></figure><h4>Data Summarization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QCOXEjiJ8uK49HYj" /><figcaption>Photo by <a href="https://unsplash.com/@kchance8?utm_source=medium&amp;utm_medium=referral">Kelsey Chance</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Awesome, you have made it till the last section of this article and I hope it’s going well. Summarization is the crux of any data analysis process, we are not done yet as there are so many things to be done using pandas for <strong>Data Wrangling, Plots and Visualization and Statistical Modeling</strong>, which will be covered in the Part 2 , 3 and 4 of this series respectively.<br>But first, let’s get used to some summarization skills.</p><p><strong>Contents:</strong> <em>info() , describe() , value_counts() , nunique() , groupby().</em></p><pre># This method prints information about a DataFrame including the index dtype and columns, non-null values and memory usage.</pre><pre>df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iiR1lQcwRIJ5enqljGxrqA.png" /></figure><pre># This function will describe you numerical as well as categorical data will all important stats at a glance.</pre><pre>df.describe(percentiles=None, include=None, exclude=None, datetime_is_numeric=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_VkLUaYPqAxguWC_r_lJNQ.png" /></figure><ul><li><strong>percentile</strong> attribute represents the quartile range of the dataset (25% , 50% and 75% of the data)</li><li><strong>std</strong> is the standard deviation of the observations, <strong>mean</strong> is the mean of the values</li><li><strong>Count</strong> is the total number of observations, <strong>min -max </strong>is minimum value and maximum value in the dataset.</li></ul><p>By default this function only works for numerical columns, however if you want to get a good descriptive glance for categorical values you can do by including an “ include” object.</p><pre># In my dataset , I only have one categorical column.</pre><pre>df.describe(include=&#39;object&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*pnAjXGLWk6LVrA-py3L5AA.png" /></figure><pre># value_counts() function will give you the count of all different types of values available in the Dataframe or series.</pre><pre>df[&#39;senior_citizens&#39;].value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*yA9NjJI1we0cVTg1U4XD3w.png" /></figure><pre># unique() and nunique() function will give you all the unique values in a particular series and number of unique values in the series respectively.</pre><pre>df[&#39;senior_citizens&#39;].unique()</pre><pre>df[&#39;senior_citizens&#39;].nunique()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*atWU6E2bZHp53nxpHUUHxw.png" /></figure><pre>## A groupby operation involves some combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups.</pre><pre>df.groupby(&#39;sex&#39;).count()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U3QwLdZDsCw2VKUjxtDsmQ.png" /></figure><p>Here, the first parameter function takes is the “ by” parameter and it will group rest of all the column against it. Similarly you can use any other categorical feature to group rest of the columns. It can also take list of values as a “ by ” parameter and will create a multi-index dataframe.</p><pre>df.groupby([&#39;sex&#39; , &#39;senior_citizens&#39;]).count()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PECpOtPN20h_YzdnBxaMTg.png" /></figure><p>Plus, you can filter out how many columns you want to actually group and only display the results for those specific columns. Use list comprehension to pass the label of columns .</p><pre>df.groupby([&#39;sex&#39; , &#39;senior_citizens&#39;])[[&#39;age&#39; , &#39;cp&#39; , &#39;chol&#39; , &#39;fbs&#39;]].count()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MU4jmu4LTXzOVOHGv675rQ.png" /></figure><p><strong>Conclusion.</strong></p><ul><li>We used couple of ways to import out data using pandas library, read.csv() and read.excel().</li><li>Selection , indexing of the data using label based or integer based labels using by loc , iloc functions.</li><li>We also looked how to work with date datatypes in a dataframe, different parameters in datetime functions and how it can be used to create new features.</li><li>Handling missing values and identifying reasons behind the missing values.</li><li>Multiple data summarization functions in Pandas, which make the exploration on datasets much easy and interesting.</li></ul><p>Thank you for reading 1st part of my article. Now you have a good understanding of basic functionalities and you may go to part 2 now and proceed with Data Wrangling article.</p><h3>Other articles.</h3><ul><li><a href="https://datasciencestuff.medium.com/complete-guide-to-pandas-library-python-code-part-2-4-4c0d9d9bd511">Part 2</a> and <a href="https://datasciencestuff.medium.com/complete-guide-to-pandas-library-python-code-part-3-4-6bc11f9465d0">Part 3</a> are linked here, do check it out incase if you haven’t already.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=420cd5bd8249" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/complete-guide-to-pandas-library-python-code-part-1-4-420cd5bd8249">Complete guide to Pandas library (Python Code) — Part 1 / 4</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>