<?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 Arsalan Zafar on Medium]]></title>
        <description><![CDATA[Stories by Arsalan Zafar on Medium]]></description>
        <link>https://medium.com/@arsalan_zafar?source=rss-e6f60ae08b5e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_zkbXgmQMCs0F3TGAVBTTA.png</url>
            <title>Stories by Arsalan Zafar on Medium</title>
            <link>https://medium.com/@arsalan_zafar?source=rss-e6f60ae08b5e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 05:04:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arsalan_zafar/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[Scatter plot with Seaborn]]></title>
            <link>https://medium.com/@arsalan_zafar/scatter-plot-with-seaborn-de322222de12?source=rss-e6f60ae08b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/de322222de12</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Arsalan Zafar]]></dc:creator>
            <pubDate>Mon, 14 Nov 2022 03:43:11 GMT</pubDate>
            <atom:updated>2022-11-14T03:43:11.442Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bA4IEVO_ktr7NVOG0grxLw.jpeg" /><figcaption><a href="https://pixabay.com/service/license/">Pixabay License</a> Free for commercial use <br>No attribution required</figcaption></figure><h3>What are we going to learn today?</h3><p>In this article, we will learn how to create a scatter plot using Seaborn.</p><p>In a scatter plot, dots show the values of two separate numerical variables on the x-axis and y-axis. Scatter plots are essential in statistics because they may display the strength of a correlation between two variables (X and Y).</p><h3>Why is it important to learn?</h3><p>It is essential to learn because of the following reasons:</p><ul><li>It shows the relationship (positive and negative) and trend between the two variables.</li><li>It helps to find the data point’s minimum, maximum, and outliers.</li><li>It shows how much one variable affects another variable.</li><li>It helps you in predicting the behavior of one variable (a dependent variable) depending on the measurement of the other variable (independent)</li></ul><h3>How can we achieve today’s goal?</h3><p>The plan for today is as follows:</p><ul><li>Scatter plot using Seaborn</li><li>Scatter plot with <strong>hue</strong> Parameter</li><li>Scatter plot with <strong>hue and size</strong> Parameter</li><li>Bonus with replot</li><li>Conclusion</li></ul><p>Let’s import the required library.</p><blockquote>Input</blockquote><pre>import pandas as pd</pre><pre>from matplotlib import pyplot as plt</pre><pre>import seaborn as sns</pre><pre>sns.set(style=”darkgrid”)</pre><p>We will use the tips data set for this article. You can load these data sets direct from Seaborn.</p><blockquote>Input</blockquote><pre>tips = sns.load_dataset(‘tips’)</pre><pre>tips.head()</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*PjPSF_HIguZqrLhkG1PR2A.png" /></figure><h3>Scatter plot using Seaborn</h3><p>To plot a scatter plot, we will use the Seaborn <strong>scatterplot</strong> method, using two numerical columns on the x and y-axis, respectively.</p><p>It shows a positive correlation as we can see that by increasing, the amount of total bill tip is also increasing.</p><blockquote>Input</blockquote><pre>sns.scatterplot(x=’total_bill’, y=’tip’, data=tips);</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*Jh2aWdDFxhyKBcOqxi_FmA.png" /></figure><h3>Scatter plot with <strong>hue</strong> parameter</h3><p>Another critical parameter, <strong>hue</strong>, is used for color encoding. It means if we set hue equal to sex (column), it shows the scatter plot for each male and female.</p><blockquote>Input</blockquote><pre>sns.scatterplot(x=’total_bill’, y=’tip’, data=tips, hue=’sex’);</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*EAJM8inbrivg_mzPj_1sCA.png" /></figure><h3>Scatter plot with <strong>hue and size</strong> parameter</h3><p>The <strong>hue</strong> parameter can be used with the <strong>size</strong> parameter. We can set hue equal to size (column in the data set) and <strong>size</strong> equal to <strong>size</strong> (column in the data set).</p><p>There are five unique sizes (1,2,3,4,5,6) in the size column, showing six different colors with different sizes (1 to 6).</p><blockquote>Input</blockquote><pre>tips[‘size’].unique()</pre><pre>sns.scatterplot(x=’total_bill’, y=’tip’, data=tips, hue=’size’, size=’size’, palette=’viridis’)</pre><pre>plt.show()</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*iLwWDf0ZIMWWQSuVPsz_eQ.png" /></figure><p>The above plot we can visualize differently, like with different sizes, we can also differentiate which data point is for male and female. We need to add a few parameters to do this.</p><p>We will set <strong>hue </strong>equal to <strong>sex</strong>, <strong>size</strong> equal to size (column name in the data set), and sizes is a parameter in which we give the <strong>range (20,200)</strong> for data points size.</p><blockquote>Input</blockquote><pre>plt.figure(figsize=(10,7))<br>sns.scatterplot(x=&#39;total_bill&#39;, y=&#39;tip&#39;, data=tips, hue=&#39;sex&#39;, size=&#39;size&#39;, sizes=(20,200))<br>plt.show()sns.scatterplot(x=’total_bill’, y=’tip’, data=tips, hue=’sex’, size=’size’, sizes=(20,200))</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X7v-TUBHWJM_02-DFWPATQ.png" /></figure><h3>Bonus</h3><p>We can use <strong>relplot </strong>to combine <strong>scatterplot</strong> and <strong>FacetGrid </strong>(The <strong>FacetGrid </strong>object takes a data frame as input and the names of variables that make up the grid’s <strong>row</strong>, <strong>column</strong>, or <strong>hue</strong> dimensions.)</p><p>To visualize a <strong>relplot</strong>, we will pass a few parameters in the <strong>relplot</strong> method, including <strong>col</strong> and <strong>row</strong>.</p><blockquote>Input</blockquote><pre>sns.relplot(x=’total_bill’, y=’tip’, data=tips, hue=’day’, col=’time’, row=’sex’);</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zHzfeTuEwzW5pRp1aSqXGA.png" /></figure><h3>Conclusion</h3><p>This article covered the scatter plot using the Seaborn. Thank you for reading hope you found it helpful.</p><p>Check out the rest of my articles <a href="https://medium.com/@arsalan_zafar">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de322222de12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Box Plot with Seaborn]]></title>
            <link>https://medium.com/@arsalan_zafar/box-plot-with-seaborn-4f4fed570f7e?source=rss-e6f60ae08b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f4fed570f7e</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Arsalan Zafar]]></dc:creator>
            <pubDate>Wed, 02 Nov 2022 19:24:50 GMT</pubDate>
            <atom:updated>2022-11-02T19:24:50.355Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AGQjlhXvumNPjGG7cBCjNQ.jpeg" /><figcaption><a href="https://pixabay.com/service/license/">Pixabay License</a> Free for commercial use <br>No attribution required</figcaption></figure><h3>What are we going to learn today?</h3><p>In this article, we will learn how to create a box plot using Seaborn. A box plot is a type of chart that is often used in exploratory data analysis.</p><p>It is a standard method of visualizing data distribution and it uses a five-number summary — the minimum, first quartile (Q1), median (Q2), third quartile (Q3), and “maximum”.</p><p>Box plot also tells about skewness and outliers in the data.</p><h3>Why is it important to learn?</h3><p>Few reasons to learn box plot are:</p><ul><li>Box plot can show several statistical measures in a compact form.</li><li>It can help detect outliers in data.</li><li>It can help determine the symmetry and skewness of the data. A</li></ul><h3>How can we achieve today’s goal?</h3><p>The plan for today is:</p><ul><li>Create a box plot using Python Seaborn</li><li>Fix the values on the x-axis according to the data</li><li>Box plot with a categorical variable</li><li>Using hue parameter</li><li>Box plot of each numerical in the data set</li><li>Adding jitter</li><li>Conclusion</li></ul><p>Let’s import the required library.</p><blockquote>Input</blockquote><pre>import pandas as pd</pre><pre>import numpy as np</pre><pre>from matplotlib import pyplot as plt</pre><pre>import seaborn as sns</pre><p>We will use the <strong>tips</strong> and <strong>iris</strong> dataset for this article. You can load these datasets directly from Seaborn.</p><p>Let’s load the datasets using the<strong> load_dataset</strong> method in Seaborn.</p><blockquote>Input</blockquote><pre>tips = sns.load_dataset(‘tips’)</pre><pre>iris = sns.load_dataset(‘iris’)</pre><p><strong>Create a box plot using Python Seaborn</strong></p><p>To visualize a box plot, we will use the Seaborn method <strong>boxplot</strong> in which two parameters will be passed <strong>x</strong> and<strong> data</strong>.</p><blockquote>Input</blockquote><pre>sns.boxplot(x=’total_bill’, data=tips);</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*yhwayljWcwG-iKoSR2tAIg.png" /></figure><p>In the above plot, we visualize a box plot for <strong>total_bill</strong>. It shows the 5-number descriptive statistics summary using a box plot.</p><h3>Fix the values on the x-axis according to the data</h3><p>But the value on the <strong>x-axis</strong> having step is <strong>10</strong>. We can change this with the help of the <strong>matplotlib xticks</strong> function.</p><blockquote>Input</blockquote><pre>sns.boxplot(x=’total_bill’, data=tips);</pre><pre>plt.xticks(np.arange(1,55,3)); # np.arange(start, stop, step)</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*IS3Y_SVvXQNrK90vp0YeGQ.png" /></figure><p>We can visualize a box plot using categorical variables. It will create a box plot for each day in the data set.</p><h3>Box plot with a categorical variable</h3><p>Let’s pass the day column on the <strong>x</strong> parameter and the <strong>total_bill</strong> column on <strong>y</strong>.</p><blockquote>Input</blockquote><pre>sns.boxplot(x=’day’, y=’total_bill’, data=tips);</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*vogGrDZzB0HTKqW01eWGyg.png" /></figure><h3>Using the hue parameter</h3><p>If you want more in-depth knowledge from the data set, you can use the <strong>hue</strong> parameter, which we discussed in the bar charts.</p><p>If we set <strong>hue</strong> equal to <strong>sex</strong> (column) in the same plot above, it will also show the box plot of each day for <strong>males</strong> and <strong>females</strong> separately.</p><blockquote>Input</blockquote><pre>sns.boxplot(x=’day’, y=’total_bill’, hue=’sex’, data=tips);</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*jom0YNl9XCPnwM5lipv9ew.png" /></figure><h3>Box plot of each numerical in the data set</h3><p>If we give the whole data set to a box plot, it will create a box plot of each numerical column present in the data set.</p><p>In iris data set there are four numerical columns named <strong>sepal_length, sepal_width, petal_length, _petal_width.</strong></p><blockquote>Input</blockquote><pre>sns.boxplot(data=iris);</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*vx0-wDgVkVZ4wX7q3jCAqA.png" /></figure><h3>Adding Jitter</h3><p>If we see the box plot of<strong> Friday</strong>, it seems that <strong>Friday</strong> has higher or equal values than <strong>Thursday</strong>, but this is not the case because the box plot only shows the summary.</p><p>If you want to see the amount of data you are working on, adding <strong>jitter</strong> to the plot can make the plot more insightful.</p><blockquote>Input</blockquote><pre>sns.boxplot(x=’day’, y=’total_bill’, data=tips);</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*vogGrDZzB0HTKqW01eWGyg.png" /></figure><p>We will use the <strong>stripplot</strong> function from Seaborn to add a jitter on the box plot.</p><blockquote>Input</blockquote><pre>sns.boxplot(x=’day’, y=’total_bill’, data=tips);</pre><pre>sns.stripplot(x=’day’, y=’total_bill’, data=tips, color=’black’, jitter=0.2);</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*_9mj-hpheQxebmsjJFhBVQ.png" /></figure><p>And now you can see new patterns. Before making any assumption that Friday has more or fewer values than the others, it is visible that Friday has a small sample size compared to others.</p><h3>Conclusion</h3><p>This article covered the box plot with real-world datasets. Thank you for reading hope you found it helpful. Check out the rest of my articles <a href="https://medium.com/@arsalan_zafar">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f4fed570f7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pie Charts with Python Matplotlib]]></title>
            <link>https://medium.com/@arsalan_zafar/pie-charts-with-python-matplotlib-ba152f3c4774?source=rss-e6f60ae08b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba152f3c4774</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Arsalan Zafar]]></dc:creator>
            <pubDate>Wed, 26 Oct 2022 01:50:13 GMT</pubDate>
            <atom:updated>2022-10-26T01:50:13.082Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yy3PdSbh0mxL-9ogzM_W5Q.jpeg" /><figcaption><a href="https://pixabay.com/service/license/">Pixabay License</a> Free for commercial use <br>No attribution required</figcaption></figure><h3>What are we going to learn today?</h3><p>Today we will learn about Pie Charts using <strong>matplotlib</strong>. A circle is divided into sectors ( represents a particular category) on a pie chart, each sector illustrating a proportion of the total.</p><p>The sum of the sectors equals 100%. A pie chart requires a list of both categorical and numerical variables.</p><p><strong>To make a better-looking Pie chart, always remember the following:</strong></p><ul><li>Avoid comparing too many pie charts by placing them side by side.</li><li>Don’t use too many categories</li><li>Always use a legend aside.</li></ul><h3>Why is it important to learn?</h3><p>The main reason to learn about Pie chart is that it visually represents data as a fractional part of a whole. It enables the audience to comprehend information quickly or to compare data rapidly to perform an analysis.</p><p>It is simple and easy to understand.</p><h3>How can we achieve today’s goal?</h3><p>The plan for today is as follows:</p><ul><li>Define the problem</li><li>Plot a pie chart on a real-world data set</li><li>Add percentage on the pie chart</li><li>Explode a slice</li><li>Changing edge color</li><li>Conclusion</li></ul><p>Let’s import the required libraries.</p><blockquote>Input</blockquote><pre>import pandas as pd</pre><pre>from matplotlib import pyplot as plt</pre><p>Load data set survey2021 taken from StackOverflow, you can download this data set from <a href="https://drive.google.com/file/d/1eHC6VKsSdtz-tDwwQ0MGYrbHNn9nMzwu/view?usp=sharing">here</a>.</p><blockquote>Input</blockquote><pre>df = pd.read_csv(‘/Your File path/survey2021.csv’)</pre><p>The<strong> info</strong> method print a concise summary of a data frame.</p><blockquote>Input</blockquote><pre>df.info()</pre><blockquote>Output</blockquote><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 83439 entries, 0 to 83438<br>Data columns (total 48 columns):<br> #   Column                        Non-Null Count  Dtype  <br>---  ------                        --------------  -----  <br> 0   ResponseId                    83439 non-null  int64  <br> 1   MainBranch                    83439 non-null  object <br> 2   Employment                    83323 non-null  object <br> 3   Country                       83439 non-null  object <br> 4   US_State                      14920 non-null  object <br> 5   UK_Country                    4418 non-null   object <br> 6   EdLevel                       83126 non-null  object <br> 7   Age1stCode                    83243 non-null  object <br> 8   LearnCode                     82963 non-null  object <br> 9   YearsCode                     81641 non-null  object <br> 10  YearsCodePro                  61216 non-null  object <br> 11  DevType                       66484 non-null  object <br> 12  OrgSize                       60726 non-null  object <br> 13  Currency                      61080 non-null  object <br> 14  CompTotal                     47183 non-null  float64<br> 15  CompFreq                      52150 non-null  object <br> 16  LanguageHaveWorkedWith        82357 non-null  object <br> 17  LanguageWantToWorkWith        76821 non-null  object <br> 18  DatabaseHaveWorkedWith        69546 non-null  object <br> 19  DatabaseWantToWorkWith        58299 non-null  object <br> 20  PlatformHaveWorkedWith        52135 non-null  object <br> 21  PlatformWantToWorkWith        41619 non-null  object <br> 22  WebframeHaveWorkedWith        61707 non-null  object <br> 23  WebframeWantToWorkWith        52095 non-null  object <br> 24  MiscTechHaveWorkedWith        47055 non-null  object <br> 25  MiscTechWantToWorkWith        38021 non-null  object <br> 26  ToolsTechHaveWorkedWith       72537 non-null  object <br> 27  ToolsTechWantToWorkWith       65480 non-null  object <br> 28  NEWCollabToolsHaveWorkedWith  81234 non-null  object <br> 29  NEWCollabToolsWantToWorkWith  73022 non-null  object <br> 30  OpSys                         83294 non-null  object <br> 31  NEWStuck                      83052 non-null  object <br> 32  NEWSOSites                    83171 non-null  object <br> 33  SOVisitFreq                   82413 non-null  object <br> 34  SOAccount                     82525 non-null  object <br> 35  SOPartFreq                    67553 non-null  object <br> 36  SOComm                        82319 non-null  object <br> 37  NEWOtherComms                 82828 non-null  object <br> 38  Age                           82407 non-null  object <br> 39  Gender                        82286 non-null  object <br> 40  Trans                         80678 non-null  object <br> 41  Sexuality                     73366 non-null  object <br> 42  Ethnicity                     79464 non-null  object <br> 43  Accessibility                 77603 non-null  object <br> 44  MentalHealth                  76920 non-null  object <br> 45  SurveyLength                  81711 non-null  object <br> 46  SurveyEase                    81948 non-null  object <br> 47  ConvertedCompYearly           46844 non-null  float64<br>dtypes: float64(2), int64(1), object(45)<br>memory usage: 30.6+ MB</pre><h3>Define the Problem</h3><p>We will use a column <strong>LanguageHaveWorkedWith</strong> where every respondent writes a language they have worked. There are 83439 respondents/developers who respond to this survey.</p><blockquote>Input</blockquote><pre>df[‘LanguageHaveWorkedWith’]</pre><blockquote>Output</blockquote><pre>0        C++;HTML/CSS;JavaScript;Objective-C;PHP;Swift<br>1                                    JavaScript;Python<br>2                             Assembly;C;Python;R;Rust<br>3                                JavaScript;TypeScript<br>4                       Bash/Shell;HTML/CSS;Python;SQL<br>                             ...                      <br>83434                               Clojure;Kotlin;SQL<br>83435                                              NaN<br>83436                               Groovy;Java;Python<br>83437             Bash/Shell;JavaScript;Node.js;Python<br>83438           Delphi;Elixir;HTML/CSS;Java;JavaScript<br>Name: LanguageHaveWorkedWith, Length: 83439, dtype: object</pre><blockquote>Input</blockquote><pre>df[‘LanguageHaveWorkedWith’].shape</pre><blockquote>Output</blockquote><pre>(83439,)</pre><p>We will take a list of 5 languages (<strong>‘Python’, ‘SQL’, ‘JavaScript’, ‘HTML/CSS’, ‘Kotlin’</strong>) and extract the number of languages a developer uses out of <strong>83439</strong>. For that, we will write Pandas <strong>str. contains </strong>method (it is used to test if pattern or text is included within a string of series). In our example the list of languages is our pattern. And then, we will pass that matched pattern to the data frame and take the shape of every language.</p><blockquote>Input</blockquote><pre>lang_list = [‘Python’, ‘SQL’, ‘JavaScript’, ‘HTML/CSS’, ‘Kotlin’]</pre><pre>for item in lang_list:</pre><pre>filt = df[‘LanguageHaveWorkedWith’].str.contains(item, na=False)</pre><pre>print(item, “:”, df.loc[filt, ‘LanguageHaveWorkedWith’].shape)</pre><blockquote>Output</blockquote><pre>Python : (39792,)<br>SQL : (38835,)<br>JavaScript : (53587,)<br>HTML/CSS : (46259,)<br>Kotlin : (6866,)</pre><p>In the above output, 39792 developers use Python out of 83439. Let’s convert the result into two lists.</p><blockquote>Input</blockquote><pre>label_s = [‘Python’, ‘SQL’, ‘JavaScript’, ‘HTML/CSS’, ‘Kotlin’]</pre><pre>lang_slices = [39792, 38835, 53587, 46259, 6866]</pre><blockquote>Output</blockquote><h3>Plot a pie chart on a real-world data set</h3><p>To plot a pie chart, we will use the <strong>pie</strong> method from <strong>matplotlib</strong> and pass two parameters (a list of categorical and numerical data).</p><blockquote>Input</blockquote><pre>plt.pie(lang_slices, labels=label_s);</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*M0PsQavkYQwnDxH9-jc1hw.png" /></figure><h3>Add percent on the pie chart</h3><p>If you want to add a percentage on each slice, we will use the <strong>autopct </strong>parameter, which displays the percent value using python string formatting.</p><blockquote>Input</blockquote><pre>plt.pie(lang_slices, labels=label_s, autopct=’%.1f’);</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*_NpSXHFl5x3YcRyQ1OufMw.png" /></figure><p>To add a percent sign with numbers, write <strong>%%</strong> in the end.</p><blockquote>Input</blockquote><pre>plt.pie(lang_slices, labels=label_s, autopct=’%.1f%%’);</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*hoFrLZe5ed1CESCrVuj00A.png" /></figure><h3>Explode a slice</h3><p>Let’s say you want to focus on one slice. We can do this by the <strong>explode </strong>parameter.</p><p>In the <strong>matplotlib</strong>, the <strong>explode</strong> parameter makes one of the pie chart slices stand out.</p><p>The <strong>explode</strong> parameter takes a list of numbers equal to the items in a pie chart. In our example, Python is the first item in a list we give to the pie chart. If we want to explode the Python, we set its value to 0.1.</p><p>You can choose 0.2 or 0.3, but at most, this.</p><blockquote>Input</blockquote><pre>plt.pie(lang_slices, labels=label_s, autopct=’%1.1f%%’, explode=[0.1, 0, 0, 0, 0]);</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*i_ybtlNBwzBSSUcU-3Fppw.png" /></figure><h3>Changing edge color</h3><p>There is another parameter, <strong>wedgeprops</strong>, for changing the edge color. It takes a dictionary where we pass a key-value pair.</p><blockquote>Input</blockquote><pre>plt.pie(lang_slices, labels=label_s, autopct=’%1.1f%%’, wedgeprops={‘edgecolor’: ‘white’}, explode= [0.1, 0, 0, 0, 0]);</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*PSxgVPiI00MlOqGU27giQg.png" /></figure><h3>Conclusion</h3><p>This article covered the Pie Chart using matplotlib. Thank you for reading hope you found it helpful. Here is a <a href="https://medium.com/@arsalan_zafar">link</a> to the rest of my data science articles on Medium.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba152f3c4774" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Histogram with Python Seaborn]]></title>
            <link>https://medium.com/@arsalan_zafar/histogram-with-python-seaborn-6385593dfac4?source=rss-e6f60ae08b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6385593dfac4</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Arsalan Zafar]]></dc:creator>
            <pubDate>Wed, 19 Oct 2022 20:46:06 GMT</pubDate>
            <atom:updated>2022-10-25T20:39:36.541Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FUcmGopxosuR07MIeci7HA.jpeg" /><figcaption><a href="https://pixabay.com/service/license/">Pixabay License</a> Free for commercial use <br>No attribution required</figcaption></figure><h3>What are we going to learn today?</h3><p>This article will teach us how to create a <strong>histogram</strong> using Seaborn.</p><p>A histogram represents statistical data that uses rectangles to display the frequency of data categories in a series of equal-sized numerical intervals.</p><p>A histogram is typically used with continuous data like temperature, time, and weight.</p><h3>Why is it important to learn?</h3><p>Histograms can be used to compare the distribution of numerical data across different bins using a sample distribution.</p><p>The median and distribution of the data can also be determined using histograms. It can help to detect outliers and any gaps in the data.</p><h3>How can we achieve today’s goal?</h3><p>Plan for today is:</p><ul><li>Histogram with Stack overflow survey data set</li><li>Adjustment of bins</li><li>Vertical mean and median on graph</li><li>Histogram of the entire data set</li><li>Histogram of discrete column</li><li>Conclusion</li></ul><p>Let’s import the required libraries and set the plot style.</p><blockquote>Input</blockquote><pre>import pandas as pd</pre><pre>import numpy as np</pre><pre>from matplotlib import pyplot as plt</pre><pre>import seaborn as sns</pre><pre>plt.style.use(‘fivethirtyeight’) # using graph style fivethirtyeight</pre><p>The data set can be downloaded from <a href="https://stackoverflow.blog/2020/07/27/public-data-release-of-stack-overflows-2020-developer-survey/">here</a>. Now lets read the survey2020 taken from StackOverflow into a data frame.</p><blockquote>Input</blockquote><pre>df = pd.read_csv(‘/Your data set location/survey_2020.csv’)</pre><pre>df.head() # First five rows</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*raC1tye8DZoaHZMUssK2zg.png" /><figcaption>Output is cropped</figcaption></figure><h3>Histogram with Stack overflow survey data set</h3><p>Let’s create the histogram and check the distribution of the age column from which we can get an idea of which age group is the highest to respond to this survey.</p><blockquote>Input</blockquote><pre>sns.histplot(data=df, x= ‘Age’);</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*bOblZIFuQVP-kY3YKsDuuw.png" /></figure><p>The above chart is hard to interpret as it only shows one bin (0 to 50) from this we cannot decide clearly what number of people are between 20 to 40.</p><h3>Adjustment of bins</h3><p>To adjust the bins in the histogram, <strong>seaborn</strong> gives one parameter called <strong>bins</strong>, where we pass a <strong>list</strong> of numbers, and the histogram will create according to the defined bins in the list.</p><blockquote>Input</blockquote><pre>sns.histplot(data=df, x=’Age’, bins=[10,20,30,40,50,60,70,80,90,100]);</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*f9cQY70JPkbzQ-1Z23jJgw.png" /></figure><h3>Vertical mean and median on graph</h3><p>We can flip the plot by assigning the data variable to the <strong>y axis</strong>:</p><blockquote>Input</blockquote><pre>sns.histplot(data=df, y=’Age’, bins=[10,20,30,40,50,60,70,80,90,100]);</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*Kz2T1qTLWp91lSvBWJGpVA.png" /></figure><p>Another thing is if you want to see the <strong>mean </strong>and median of the data in histogram distribution, you can do it with the help of the <strong>matplotlib</strong> <strong>axvline</strong> function. Using this function, we can add a vertical line across the axis.</p><p>First, let’s compute the mean and median of the age column.</p><blockquote>Input</blockquote><pre>print(‘Mean Age: ‘,df[‘Age’].mean(), ‘\n’)</pre><pre>print(‘Median Age: ‘,df[‘Age’].median())</pre><blockquote>Output</blockquote><pre>Mean Age:    30.83411081283281 <br><br>Median Age:  29.0</pre><p>We will use the same plot as above and add a vertical line using matplotlib <strong>axvline</strong>, in which we will pass <strong>mean_age</strong> and <strong>median_age</strong> with parameters <strong>colour, label</strong> and <strong>linewidth</strong>.</p><blockquote>Input</blockquote><pre>sns.histplot(data=df, x=’Age’, bins=[10,20,30,40,50,60,70,80,90,100])</pre><pre>mean_age = 30</pre><pre>median_age = 25</pre><pre>plt.axvline(mean_age, color=’orange’, label=’Mean Age’, linewidth=3)</pre><pre>plt.axvline(median_age, color=’black’, label=’median_age’, linewidth=3)</pre><pre>plt.legend()</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*c_ExTwMc5jW0VujJC6iYvQ.png" /></figure><h3>Histogram of the entire data set</h3><p>Let’s import another data set (tips) to explore more about the histogram. It can downloaded from here.</p><blockquote>Input</blockquote><pre>tips = sns.load_dataset(‘tips’)</pre><pre>tips.head() # shows first 5 rows of the dataset</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*6zzIVZgS5gin2sXfWAY7og.png" /></figure><p>If we provide the whole data set without assigning x or y, a histogram is created for each numerical column in the data set, with a different color for each column.</p><blockquote>Input</blockquote><pre>sns.histplot(data=tips);</pre><blockquote>Ouput</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*K2y8nIMH9oaOWQEumn0g5g.png" /></figure><p>With hue (an important parameter used for color encoding the <strong>column</strong> in the data frame) mapping, we can create several histograms from a long-form data set.</p><blockquote>Input</blockquote><pre>sns.histplot(data=tips, x=’total_bill’, hue=’sex’);</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*FyEHfMZ-aLzpH_nMKkKkFA.png" /></figure><h3>Histogram of discrete variable column</h3><p>By default, the histogram (bar’s height) shows a count, but we can change this into <strong>‘frequency’, ‘density’, ‘probability’, ‘proportion’, ‘percent</strong>’ with the help of the <strong>stat</strong> parameter. The ‘probability’, ‘proportion’, ‘percent’ makes more sense for discrete variables.</p><blockquote>Input</blockquote><pre>sns.histplot(data=tips, x=’size’, stat=’percent’, discrete=True)</pre><pre>plt.show()</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*cFG_-E4LvbEqjNYqyDA0uQ.png" /></figure><h3>Conclusion</h3><p>This article covered the histogram with practical examples. Thank you for reading hope you found it helpful. Check out the rest of my articles <a href="https://medium.com/@arsalan_zafar">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6385593dfac4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bar Plots in Seaborn]]></title>
            <link>https://medium.com/@arsalan_zafar/bar-plots-in-seaborn-6a81c453e0c4?source=rss-e6f60ae08b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a81c453e0c4</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Arsalan Zafar]]></dc:creator>
            <pubDate>Tue, 18 Oct 2022 16:21:49 GMT</pubDate>
            <atom:updated>2022-10-25T20:38:48.486Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kEe8bDScLaie1K4kxh_NvA.jpeg" /><figcaption>Pixabay Free for commercial use <br>No attribution required</figcaption></figure><h3>What are we going to learn today?</h3><p>In this article, we will learn how to interpret data using a bar plot using <strong>Seaborn</strong>.</p><p>A bar plot is the most common visualization tool that uses bars to compare data among categories. It shows the relationship between a numeric and a categorical variable. The size of the bar represents its numeric value.</p><h3>Why is it important to learn?</h3><p>There are various reasons to use bar plot, which makes it essential to learn. A few are mentioned below.</p><ul><li>It summarizes extensive data in visual form.</li><li>It makes the data more presentable and easy to understand.</li><li>It also helps compare data better and clarify trends better than the tables.</li></ul><h3>How can we achieve today’s goal?</h3><p>Plan for today is:</p><p>Bar plot of Stack overflow survey data set</p><ul><li>Define the problem</li><li>Vertical Bar Plot</li><li>Horizontal Bar Plot</li></ul><p>Bar plot with the Titanic data set</p><ul><li>Choosing estimator (mean, median, mode)</li><li>HUE Parameter</li></ul><p>Conclusion</p><p>Let’s get started with importing the relevant libraries.</p><blockquote>Input</blockquote><pre>import pandas as pd<br>from matplotlib import pyplot as plt<br>import seaborn as sns<br>import numpy as np </pre><h3>Bar plot of Stack overflow survey data set</h3><p>We will use the <strong>Stackoverflow survey 2021</strong> data set for this article. You can download the clean data set from <a href="https://drive.google.com/file/d/1ns50rF7KVTzekHCUOZEUUMuxVE5epVm_/view?usp=sharing">here</a>.</p><p>Let’s read the data set using the <strong>read_csv</strong> method in pandas.</p><blockquote>Input</blockquote><pre>data = pd.read_csv(&#39;/content/drive/MyDrive/Article upload/dataset/survey2021/survey2021.csv&#39;)</pre><p>First five rows of the data set.</p><blockquote>Input</blockquote><pre>data.head()</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C3qCRLcMYfyD7r2IjMWaQA.png" /><figcaption>Output is cropped</figcaption></figure><p><strong>data.columns</strong> give the list of all 48 columns in the data set.</p><blockquote>Input</blockquote><pre>data.columns</pre><blockquote>Output</blockquote><pre>Index([&#39;ResponseId&#39;, &#39;MainBranch&#39;, &#39;Employment&#39;, &#39;Country&#39;, &#39;US_State&#39;,<br>       &#39;UK_Country&#39;, &#39;EdLevel&#39;, &#39;Age1stCode&#39;, &#39;LearnCode&#39;, &#39;YearsCode&#39;,<br>       &#39;YearsCodePro&#39;, &#39;DevType&#39;, &#39;OrgSize&#39;, &#39;Currency&#39;, &#39;CompTotal&#39;,<br>       &#39;CompFreq&#39;, &#39;LanguageHaveWorkedWith&#39;, &#39;LanguageWantToWorkWith&#39;,<br>       &#39;DatabaseHaveWorkedWith&#39;, &#39;DatabaseWantToWorkWith&#39;,<br>       &#39;PlatformHaveWorkedWith&#39;, &#39;PlatformWantToWorkWith&#39;,<br>       &#39;WebframeHaveWorkedWith&#39;, &#39;WebframeWantToWorkWith&#39;,<br>       &#39;MiscTechHaveWorkedWith&#39;, &#39;MiscTechWantToWorkWith&#39;,<br>       &#39;ToolsTechHaveWorkedWith&#39;, &#39;ToolsTechWantToWorkWith&#39;,<br>       &#39;NEWCollabToolsHaveWorkedWith&#39;, &#39;NEWCollabToolsWantToWorkWith&#39;, &#39;OpSys&#39;,<br>       &#39;NEWStuck&#39;, &#39;NEWSOSites&#39;, &#39;SOVisitFreq&#39;, &#39;SOAccount&#39;, &#39;SOPartFreq&#39;,<br>       &#39;SOComm&#39;, &#39;NEWOtherComms&#39;, &#39;Age&#39;, &#39;Gender&#39;, &#39;Trans&#39;, &#39;Sexuality&#39;,<br>       &#39;Ethnicity&#39;, &#39;Accessibility&#39;, &#39;MentalHealth&#39;, &#39;SurveyLength&#39;,<br>       &#39;SurveyEase&#39;, &#39;ConvertedCompYearly&#39;],<br>      dtype=&#39;object&#39;)</pre><h4>Define the Problem</h4><p>We want to find out what are the top 10 programming languages using the column<strong> LanguageHaveWorkedWith</strong>. We will extract information from 83439 developers (one row is equal to 1 developer). Then we will plot that information in bar plot which will be easily interpreted by even non-tech people.</p><p><strong>Note</strong>.I have done some data cleaning and pre-processing to extract the count of language every developer uses. And write it into the CSV file.</p><p>We will read that file and use the two columns <strong>‘ Language’, ‘NumOfPeopleUses’</strong> with the <strong>usecols</strong> parameter.</p><blockquote>Input</blockquote><pre>df = pd.read_csv(‘data.csv’, usecols=[‘Language’, ‘NumOfPeopleUses’])</pre><pre>df.head(10)</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*5s5CvKh1W5bzKB9S2oocqw.png" /></figure><h4><strong>Vertical Bar Plot</strong></h4><p>Let’s create a bar plot to visualize the top 5 most used languages.</p><p>In order to visualize a bar plot, we will use the seaborn method <strong>barplot</strong> in which three parameters will be passed<strong> x, y</strong> and <strong>data</strong>.</p><blockquote>Input</blockquote><pre>sns.barplot(x=’Language’, y=’NumOfPeopleUses’, data=df.head(10))</pre><pre>plt.xticks(rotation=45)</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*7XtzbmQwXJ_2gmQW_NNbgw.png" /></figure><p>This is the same code above one, but I add a <strong>semicolon(;)</strong> at the end from which we can get rid of extra text like (array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), &lt;a list of 10 Text major ticklabel objects&gt;)</p><blockquote>Input</blockquote><pre>sns.barplot(x=’Language’, y=’NumOfPeopleUses’, data=df.head(10));</pre><pre>plt.xticks(rotation=45);</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Mif4V3bURu1fdzUp3ptLeQ.png" /></figure><p>Let’s visualize a bar plot of the top 20 most used languages.</p><blockquote>Input</blockquote><pre>sns.barplot(x=’Language’, y=’NumOfPeopleUses’, data=df.head(20));</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*CLykfNjfZhd80ri1kokQgw.png" /></figure><p>We can see clearly in the<strong> x-axis</strong> that <strong>Language</strong> is not visible (data is in wide form). To overcome the problem, we can plot a graph horizontally.</p><h4>Horizontal Bar Plot</h4><p>Instead of giving Language on the<strong> x-axis</strong>, we give on the <strong>y-axis</strong> and <strong>NumOfPeopleUses</strong> on the x-axis.</p><blockquote>Input</blockquote><pre>sns.barplot(x=’NumOfPeopleUses’, y=’Language’,data=df.head(20));</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*OZ_TsHu13KIKU0CkVmntCw.png" /></figure><h3>Bar plot with the Titanic data set</h3><p>Let’s explore more about bar plot, but we will use the titanic dataset this time.</p><blockquote>Input</blockquote><pre>titanic = sns.load_dataset(‘titanic’)</pre><pre>titanic.head()</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gPEpfYU3iSDOUOWlwk327w.png" /><figcaption>Output is cropped</figcaption></figure><p>In the above bar plot (survey2021), we have a count of every Language, so we have interpreted it easily. However, if we do not have a column with count. We can take two columns from the titanic data set <strong>sex</strong> on the <strong>x-axis</strong> and <strong>age</strong> on the <strong>y-axis</strong> and create a bar plot.</p><blockquote>Input</blockquote><pre>sns.barplot(x=’sex’, y=’age’, data=titanic);</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*OD_dyRzLpelhHmGsXsOM0A.png" /></figure><h4>Choosing estimator (mean, median, mode)</h4><p>In the above plot numbers, you see a <strong>mean</strong> age of male and female because the bar plot also estimates the central tendency of a numeric variable.</p><p>Seaborn bar plot has one parameter, <strong>estimator</strong>, which is used for the statistical function to estimate within each categorical bin. It is set to <strong>mean </strong>by default, but we can change it into another statistical function like median or mode.</p><blockquote>Input</blockquote><pre>sns.barplot(x=’sex’, y=’age’, estimator=np.mean, data=titanic);</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*yo7xbfx7OjHTpFPMSZx1UA.png" /></figure><p>Here estimator is the <strong>median</strong>.</p><blockquote>Input</blockquote><pre>sns.barplot(x=’sex’, y=’age’, estimator=np.median, data=titanic);</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*GoZ-15j0szzCwLGoUH5DHw.png" /></figure><h4>HUE Parameter</h4><p>We can also change the color of bars using <strong>palette</strong> parameters.</p><blockquote>Input</blockquote><pre>sns.barplot(x=’sex’, y=’age’, palette=’Oranges_r’, data=titanic);</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*JRDts3yKPJ-OBUCZ8X1KJQ.png" /></figure><p>Another important parameter is <strong>HUE</strong> which is used for color encoding the column in the data frame.</p><p>The advantage of this parameter is that it gives a more in-depth knowledge of the data. For example, if we set assign <strong>pclass</strong> (passenger class) now, we will see three bars for <strong>male</strong> and <strong>female</strong> for each passenger class <strong>y-axis</strong> shows the mean <strong>age</strong>.</p><blockquote>Input</blockquote><pre>sns.barplot(x=’sex’, y=’age’, hue=’pclass’, data=titanic);</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*NpTL56Wf1I9xS_LVSkKh_Q.png" /></figure><p>These black lines are <strong>ci</strong>(It is the size of confidence intervals to draw around estimated values. If set to “<strong>sd</strong>”, it will skip bootstrapping and draw the standard deviation of the observations)</p><p>If you want to remove this, just set <strong>ci</strong> equal to <strong>None</strong>.</p><blockquote>Input</blockquote><pre>sns.barplot(x=’sex’, y=’age’, hue=’pclass’,ci=None, data=titanic);</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Jh7mxEsIXXT7dQlAdUF6UQ.png" /></figure><h3>Conclusion</h3><p>This article covered the bar graph with real-world example. Thank you for reading hope you found it helpful. Check out the rest of my articles <a href="https://medium.com/@arsalan_zafar">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a81c453e0c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Seaborn]]></title>
            <link>https://medium.com/@arsalan_zafar/introduction-to-seaborn-c50d0052919a?source=rss-e6f60ae08b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c50d0052919a</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Arsalan Zafar]]></dc:creator>
            <pubDate>Mon, 22 Aug 2022 06:36:49 GMT</pubDate>
            <atom:updated>2022-08-22T06:37:44.364Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to Data Visualization with Seaborn &amp; Matplotlib</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S9WnImrJlxJ2N12yR2k-oA.jpeg" /><figcaption><a href="https://pixabay.com/service/license/">Pixabay License</a> Free for commercial use <br>No attribution required</figcaption></figure><h3><strong>What are we going to learn today?</strong></h3><p><strong>Seaborn</strong> and <strong>Matplotlib</strong> are python data visualization libraries. We will use them together to represent data in the form of a plot, diagram, or picture. Seaborn is more advanced, functional and organized than matplotlib. However, matplotlib makes it easy to customize the graphs. In this article we will use plot and graph interchangeably.</p><h3>Why is it important to learn?</h3><p>Data visualization helps us make sense of the data. It helps us easily grasp the context and story behind the data. It is an essential step in the business intelligence process which helps make valuable conclusions. Data visualization also helps to identify patterns and trends from the raw data. We can detect and remove outliers in a data set with the data visualization.</p><h3><strong>How are we going to achieve today’s learning goal?</strong></h3><p>Learning plan for today is:</p><p>Plan for today is:</p><ul><li>Plot style theme</li><li>Create a line plot</li><li>Customize the line plot</li></ul><p>Let us import the <strong>matplotlib</strong> and<strong> seaborn</strong> libraries.</p><blockquote>Input</blockquote><pre>from matplotlib import pyplot as plt</pre><pre>import seaborn as sns</pre><h4>Plot style theme</h4><p>Selecting a theme style add to the aesthetic value of a plot. Both <strong>seaborn </strong>and <strong>matplotlib</strong> have style themes.</p><p>There is five themes in <strong>seaborn</strong>.</p><ul><li>white</li><li>dark</li><li>whitegrid</li><li>darkgrid</li><li>ticks</li></ul><p>To set a theme in <strong>seaborn</strong> we will use the <strong>set_style()</strong> method.</p><blockquote>Input</blockquote><pre>sns.set_style(‘darkgrid’)</pre><p>For the rest of this article we will use style theme from <strong>matplotlib</strong>. Matplotlib gives 26 styles which you can be seen with the <strong>plt.style.available</strong> method.</p><blockquote>Input</blockquote><pre>plt.style.available</pre><blockquote>Output</blockquote><pre>[&#39;Solarize_Light2&#39;,<br> &#39;_classic_test_patch&#39;,<br> &#39;bmh&#39;,<br> &#39;classic&#39;,<br> &#39;dark_background&#39;,<br> &#39;fast&#39;,<br> &#39;fivethirtyeight&#39;,<br> &#39;ggplot&#39;,<br> &#39;grayscale&#39;,<br> &#39;seaborn&#39;,<br> &#39;seaborn-bright&#39;,<br> &#39;seaborn-colorblind&#39;,<br> &#39;seaborn-dark&#39;,<br> &#39;seaborn-dark-palette&#39;,<br> &#39;seaborn-darkgrid&#39;,<br> &#39;seaborn-deep&#39;,<br> &#39;seaborn-muted&#39;,<br> &#39;seaborn-notebook&#39;,<br> &#39;seaborn-paper&#39;,<br> &#39;seaborn-pastel&#39;,<br> &#39;seaborn-poster&#39;,<br> &#39;seaborn-talk&#39;,<br> &#39;seaborn-ticks&#39;,<br> &#39;seaborn-white&#39;,<br> &#39;seaborn-whitegrid&#39;,<br> &#39;tableau-colorblind10&#39;]</pre><p>In order to set a style theme in we will use <strong>plt.style.use()</strong> method.</p><blockquote>Input</blockquote><pre>plt.style.use(‘fivethirtyeight’)</pre><h4><strong>Create a line plot</strong></h4><p>A line plot is a way to display data using a numbered line.</p><p>To create a line plot, we will use the <strong>lineplot </strong>method from<strong> seaborn</strong> and then the <strong>x</strong> and<strong> y</strong> parameters, respectively.</p><blockquote>Input</blockquote><pre>sns.lineplot(x=months, y=sale2020,)</pre><pre>sns.lineplot(x=months, y=sale2021)</pre><pre>plt.show()</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*KzXNfh1A0R4HpxFC_4I3Bg.png" /></figure><h4>Customize the line plot</h4><p>The text below x-axis represents names of the months. And they are not visible clearly. We can fix this problem by rotating the text axis by 45 degrees.</p><p>For this, we will use the <strong>xticks</strong> method from <strong>matplotlib</strong> and pass <strong>rotation</strong> parameter as 45 degrees.</p><blockquote>Input</blockquote><pre>sns.lineplot(x=months, y=sale2020,)</pre><pre>sns.lineplot(x=months, y=sale2021)</pre><pre>plt.xticks(rotation=45)</pre><pre>plt.show()</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*m7HE7s7kdM8nmEH1OhgWbw.png" /></figure><p>We can also change the <strong>width</strong> of the line in the graph and add a <strong>marker</strong> for every point, making the line plot easier to see.</p><blockquote>Input</blockquote><pre>sns.lineplot(x=months, y=sale2020, marker=’o’)</pre><pre>sns.lineplot(x=months, y=sale2021, linewidth=’8&#39;)</pre><pre>plt.xticks(rotation=45)</pre><pre>plt.show()</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*VQr8CMKE0-3EHpTO0tMiqw.png" /></figure><p>The two lines look great. But what do they represent? How do we know which line represents data from 2020 vs 2021.</p><p>For this, we will use the <strong>legend</strong> mehod from matplotlib to create a legend box.</p><p>We will pass a <strong>label</strong> parameter in lineplot method from seaborn to assign a name to each line. Then we will pass the <strong>loc</strong> parameter in the legend method to select the position of the legend box from matplotlib.</p><blockquote>Input</blockquote><pre>sns.lineplot(x=months, y=sale2020, label=’Sale in 2020&#39;)</pre><pre>sns.lineplot(x=months, y=sale2021, label=’Sale in 2021&#39;)</pre><pre>plt.xticks(rotation=45)</pre><pre>plt.legend()</pre><pre># plt.legend(loc=’lower right’)</pre><pre>plt.show()</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*6e8E1LnzsX0OXBuIqb0JqA.png" /></figure><p>We can also add a title to the axis using <strong>xlabel </strong>and <strong>ylabel</strong> to make the graph easier to understand.</p><blockquote>Input</blockquote><pre>sns.lineplot(x=months, y=sale2020, label=’Sale in 2020&#39;)</pre><pre>sns.lineplot(x=months, y=sale2021, label=’Sale in 2021&#39;)</pre><pre>plt.title(“Sale of Each Months 2020–2021”)</pre><pre>plt.xlabel(‘Months’)</pre><pre>plt.ylabel(‘Sales’)</pre><pre>plt.xticks(rotation=45)</pre><pre>plt.legend()</pre><pre>plt.show()</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*XDUs9vvbS88VfzoOGFT73w.png" /></figure><p>Now lets change the figure size of a plot using the matplotlib <strong>figure</strong> method.</p><blockquote>Input</blockquote><pre>plt.figure(figsize=(10,7))</pre><pre>sns.lineplot(x=months, y=sale2020, label=’Sale in 2020&#39;)</pre><pre>sns.lineplot(x=months, y=sale2021, label=’Sale in 2021&#39;)</pre><pre>plt.title(“Sale of Each Months 2020–2021”)</pre><pre>plt.xlabel(‘Months’)</pre><pre>plt.ylabel(‘Sales’)</pre><pre>plt.xticks(rotation=45)</pre><pre>plt.legend()</pre><pre>plt.show()</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sii2iRhNSjMk2q5Sx_n66w.png" /></figure><p>Moreover, we can customize X and Y labels by increasing the font size and changing the font family and style by passing parameters like <strong>fontsize, family, fontsyle</strong>, and <strong>weight </strong>in the <strong>xlabel </strong>and <strong>ylabel </strong>methods.</p><p>Finally, if we want to save the graph on your computer, we will use the matplotlib method <strong>savefig</strong>.</p><blockquote>Input</blockquote><pre>sns.lineplot(x=months, y=sale2020, label=’Sale in 2020&#39;)</pre><pre>sns.lineplot(x=months, y=sale2021, label=’Sale in 2021&#39;)</pre><pre>plt.title(“Sale of Each Months 2020–2021”)</pre><pre>plt.xlabel(‘Months’, fontsize=20, fontstyle=’italic’)</pre><pre>plt.ylabel(‘Sales’, fontsize=20, family=’DejaVu Sans’, fontstyle=’italic’, weight=1000)</pre><pre>plt.xticks(rotation=45)</pre><pre>plt.legend()</pre><pre>plt.savefig(‘lineplot.png’)</pre><pre>plt.show()</pre><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*tm0_J3WYNQsWbu_N2jzJ0A.png" /></figure><h4>Conclusion</h4><p>In this article we have taken the first step in data visualtion using python seaborn and matplotlib libraries. Thank you for reading the article and I hope you found it helpful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c50d0052919a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reading and writing to files in Pandas]]></title>
            <link>https://medium.com/@arsalan_zafar/reading-and-writing-to-files-in-pandas-59122f7288f8?source=rss-e6f60ae08b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/59122f7288f8</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Arsalan Zafar]]></dc:creator>
            <pubDate>Mon, 09 May 2022 06:15:06 GMT</pubDate>
            <atom:updated>2022-05-09T06:15:06.930Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BoYw00CEL7Qgq6Yl8bULBQ.jpeg" /></figure><h3>What are we going to learn today?</h3><p>In this article, we will learn how to read and write different file formats in Pandas. In the real world, data comes in different formats like Excel, CSV, JSON, SQL.</p><h3>Why is it important to learn?</h3><p>As a data scientist, you will come across data stored in various file formats and databases. Knowing to load the data correctly in the data frame or series for analysis is a great skill.</p><h3>How can we achieve today’s goal?</h3><p>We will review reading and writing in different formats in which we will cover:</p><ul><li>Reading CSV and Excel files</li><li>Writing Files into CSV and Excel</li><li>Reading JSON file</li></ul><h3>How are we going to achieve today’s goal?</h3><p>We will review reading and writing in different formats in which we will cover:</p><ul><li>Reading CSV and Excel files</li><li>Writing Files into CSV and Excel</li><li>Reading JSON file</li></ul><p>Let’s import the Pandas library.</p><blockquote>Input</blockquote><pre>import pandas as pd</pre><h3>Reading CSV and Excel files</h3><p>To read the CSV file format, Pandas gives a <strong>read_csv</strong> method. Below, we are reading a CSV file. The data set we are using can be downloaded from <a href="https://insights.stackoverflow.com/survey">here</a>.</p><blockquote>Input</blockquote><pre>df = pd.read_csv(“Your File Path/survey.csv”)</pre><p>The method to read the excel file is the same as we used to read the CSV file. Instead of read_csv, we use read_excel function.</p><blockquote>Input</blockquote><pre>df = pd.read_csv(“Your File Path/survey.xlsx”)</pre><h3>Writing Files into CSV and Excel</h3><p>The developer data set we are using is from the whole world. For example, we want the data from only Canada and make another file (CSV) for this country. We will use the <strong>to_csv</strong> method and give the path where we want to store the new generated CSV file.</p><p>Let’s create a filter to extract all the data from Canada whose salary is greater than 20000</p><blockquote>Input</blockquote><pre>filt = (df[‘Country’] == ‘Canada’) &amp; (df[‘ConvertedCompYearly’] &gt; 20000)</pre><pre>ca_data = df.loc[filt]</pre><pre>ca_data</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b2W9qk56tM7eBwjPKx77kg.png" /><figcaption>Output is cropped</figcaption></figure><h4>CSV -Comma Separated Version¶</h4><p>We are writing the newly extracted dataframe (ca_data) into a CSV file.</p><blockquote>Input</blockquote><pre>ca_data.to_csv(‘ca_salary.csv’)</pre><h4>TSV -Tab Seprated Version</h4><p>Like CSV, TSV is another format. In this format, data is separated by Tab (1 tab equals four spaces).</p><p>In order to write in TSV, we will use the same method <strong>to_csv</strong>, but we will pass one additional parameter named <strong>sep</strong>, which means separator set to <strong>\t</strong>.</p><blockquote>Input</blockquote><pre>ca_data.to_csv(‘ca_salary.csv’, sep=’\t’)</pre><h4>xlsx -Excel</h4><p>For writing in an excel file, simply we will use the to_excel method.</p><blockquote>Input</blockquote><pre>ca_data.to_excel(‘ca_salary.xlsx’)</pre><h4>JSON -JavaScript Object Notation</h4><p>JavaScript Object Notation (JSON) is a standard text-based format representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).</p><p><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON">https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON</a></p><p>To write data in JSON is as simple as we did above with the <strong>to_json</strong> method, and we set the orients parameter to records and lines equal to True.</p><blockquote>Input</blockquote><pre>ca_data.to_json(&#39;ca_data.json&#39;, orient=&#39;records&#39;, lines=True)</pre><h3>Conclusion</h3><p>In this article, we learned how to read and write files in Pandas. I hope it helps you thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59122f7288f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Series analysis in Pandas]]></title>
            <link>https://medium.com/@arsalan_zafar/time-series-analysis-in-pandas-f1c9c9a20ae?source=rss-e6f60ae08b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1c9c9a20ae</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pandas]]></category>
            <dc:creator><![CDATA[Arsalan Zafar]]></dc:creator>
            <pubDate>Thu, 05 May 2022 19:58:08 GMT</pubDate>
            <atom:updated>2022-05-05T19:58:08.478Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yc55oqj301VBPBIqqUGdvg.jpeg" /></figure><h3>What are we going to learn today?</h3><p>Time Series analysis is a technique that deals with time-series data. It is a specific way of analyzing a sequence of data points gathered over time. We will learn various Pandas methods used in time series analysis.</p><h3>Why is it important to learn?</h3><p>Time Series analysis helps you identify patterns. It is also used in statistics, signal processing, pattern recognition, earthquake prediction, and weather forecasting. Good forecasting can predict the direction in which the data is changing.</p><h3>How are we going to achieve today’s learning goal?</h3><p>Today’s plan is:</p><ul><li>Date Range</li><li>Difference in dates</li><li>Changing frequency</li><li>Shifting</li><li>Time zones</li></ul><p>Let’s import the Pandas library.</p><blockquote>Input</blockquote><pre>import pandas as pd</pre><p>Let’s load the data set for apple stock (aapl.csv) that can be downloaded from <a href="https://drive.google.com/drive/folders/1Cak3ICkhqJzo0LSJ7ptx4016Clov8euM?usp=sharing">here</a>.</p><blockquote>Input</blockquote><pre>df = pd.read_csv(‘Your File path/aapl.csv’, parse_dates=[‘Date’])</pre><p>Review the first few rows</p><blockquote>Input</blockquote><pre>df.head()</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*w4VAcREoiyycKiSxq6NK2w.png" /></figure><p>Review the data type of columns.</p><blockquote>Input</blockquote><pre>df.info()</pre><blockquote>Output</blockquote><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 22 entries, 0 to 21<br>Data columns (total 6 columns):<br> #   Column  Non-Null Count  Dtype  <br>---  ------  --------------  -----  <br> 0   Date    22 non-null     object <br> 1   Open    22 non-null     float64<br> 2   High    22 non-null     float64<br> 3   Low     22 non-null     float64<br> 4   Close   22 non-null     float64<br> 5   Volume  22 non-null     int64  <br>dtypes: float64(4), int64(1), object(1)<br>memory usage: 1.2+ KB</pre><p>As we can see, the column <strong>Date</strong> is of the object type. We would have to change it to the <strong>DateTime</strong> data type for time series analysis.</p><p>We will pass the <strong>parse_dates </strong>parameter and assign the <strong>Date</strong> column to it for conversion.</p><blockquote>Input</blockquote><pre>df = pd.read_csv(‘Your File Path/aapl.csv’, parse_dates=[‘Date’])</pre><p>Review the data type of columns. Now the <strong>Date</strong> column shows as type <strong>DateTime</strong>.</p><blockquote>Output</blockquote><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 22 entries, 0 to 21<br>Data columns (total 6 columns):<br> #   Column  Non-Null Count  Dtype         <br>---  ------  --------------  -----         <br> 0   Date    22 non-null     datetime64[ns]<br> 1   Open    22 non-null     float64       <br> 2   High    22 non-null     float64       <br> 3   Low     22 non-null     float64       <br> 4   Close   22 non-null     float64       <br> 5   Volume  22 non-null     int64         <br>dtypes: datetime64[ns](1), float64(4), int64(1)<br>memory usage: 1.2 KB</pre><h3>Date Range</h3><p>In pandas, <strong>date_range()</strong> is used to return a fixed frequency <strong>DatetimeIndex</strong>. We can use this method to add a Time Series index to a data set. By default, it shows the frequency of the day.</p><p>Let’s create a date range.</p><blockquote>Input</blockquote><pre>range1 = pd.date_range(start=’6–1–2021&#39;, end=’6–30–2021&#39;)</pre><pre>range1</pre><blockquote>Output</blockquote><pre>DatetimeIndex([&#39;2021-06-01&#39;, &#39;2021-06-02&#39;, &#39;2021-06-03&#39;, &#39;2021-06-04&#39;,<br>               &#39;2021-06-05&#39;, &#39;2021-06-06&#39;, &#39;2021-06-07&#39;, &#39;2021-06-08&#39;,<br>               &#39;2021-06-09&#39;, &#39;2021-06-10&#39;, &#39;2021-06-11&#39;, &#39;2021-06-12&#39;,<br>               &#39;2021-06-13&#39;, &#39;2021-06-14&#39;, &#39;2021-06-15&#39;, &#39;2021-06-16&#39;,<br>               &#39;2021-06-17&#39;, &#39;2021-06-18&#39;, &#39;2021-06-19&#39;, &#39;2021-06-20&#39;,<br>               &#39;2021-06-21&#39;, &#39;2021-06-22&#39;, &#39;2021-06-23&#39;, &#39;2021-06-24&#39;,<br>               &#39;2021-06-25&#39;, &#39;2021-06-26&#39;, &#39;2021-06-27&#39;, &#39;2021-06-28&#39;,<br>               &#39;2021-06-29&#39;, &#39;2021-06-30&#39;],<br>              dtype=&#39;datetime64[ns]&#39;, freq=&#39;D&#39;)</pre><p>If we want to change the frequency to only business days.</p><blockquote>Input</blockquote><pre>range2 = pd.date_range(start=’6–1–2021&#39;, end=’6–30–2021&#39;, freq=’B’)</pre><pre>range2</pre><blockquote>Output</blockquote><pre>DatetimeIndex([&#39;2021-06-01&#39;, &#39;2021-06-02&#39;, &#39;2021-06-03&#39;, &#39;2021-06-04&#39;,<br>               &#39;2021-06-07&#39;, &#39;2021-06-08&#39;, &#39;2021-06-09&#39;, &#39;2021-06-10&#39;,<br>               &#39;2021-06-11&#39;, &#39;2021-06-14&#39;, &#39;2021-06-15&#39;, &#39;2021-06-16&#39;,<br>               &#39;2021-06-17&#39;, &#39;2021-06-18&#39;, &#39;2021-06-21&#39;, &#39;2021-06-22&#39;,<br>               &#39;2021-06-23&#39;, &#39;2021-06-24&#39;, &#39;2021-06-25&#39;, &#39;2021-06-28&#39;,<br>               &#39;2021-06-29&#39;, &#39;2021-06-30&#39;],<br>              dtype=&#39;datetime64[ns]&#39;, freq=&#39;B&#39;)</pre><p>Now let’s apply the business days frequency to a data set without time stamps — download the data set <a href="https://drive.google.com/file/d/1bfP4i7BTRpYHI7f9c3Z98iVws0VfCynm/view?usp=sharing">here</a>.</p><blockquote>Input</blockquote><pre>df = pd.read_csv(‘Your File Path Here/aapl_no_dates.csv’<br>df.head()</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*_z3uho1BXphWZO76g18kXg.png" /></figure><p>Now lets add <strong>range2</strong> as the index of the data set.</p><blockquote>Input</blockquote><pre>df.set_index(range2, inplace=True)</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*bcySOY-t_WavaQx0xr4Q6Q.png" /></figure><h3>Difference</h3><p>Suppose we want to see the difference of dates or extract certain days from the data set. For that purpose, we will get the difference between two frequencies with the help of the <strong>difference</strong> method.</p><p>Let’s extract the weekend days from our <strong>aapl.csv</strong> data set. We will drop the <strong>Date</strong> column and set the index as <strong>range2 </strong>which only has the business days frequency.</p><blockquote>Input</blockquote><pre>df = pd.read_csv(‘/content/drive/MyDrive/Article upload/dataset/aapl.csv’)</pre><pre>df.set_index(range2, inplace=True)</pre><pre>df.drop(columns=’Date’, inplace=True)</pre><pre>df</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*vYcPKPKaTBl7m20nIjRCQA.png" /></figure><p>Now, we will take the difference</p><blockquote>Input</blockquote><pre>range1.difference(df.index)</pre><blockquote>Output</blockquote><pre>DatetimeIndex([&#39;2021-06-05&#39;, &#39;2021-06-06&#39;, &#39;2021-06-12&#39;, &#39;2021-06-13&#39;,<br>               &#39;2021-06-19&#39;, &#39;2021-06-20&#39;],<br>              dtype=&#39;datetime64[ns]&#39;, freq=None)</pre><p>If we see the above output, we get the dates of weekend days.</p><h3>Changing frequency</h3><p>The <strong>asfreq()</strong> method converts TimeSeries to a specified frequency. Let’s change our data set to an hourly frequency. But you may ask, we don’t have hourly data. This method gives a filling method to pad/back fill missing values and place mean forward fill.</p><p>So, let’s make data into hour frequency with the help of the freq parameter set to <strong>H</strong>, which means hour.</p><pre>Input</pre><pre>df.asfreq(‘H’, method=’pad’)</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*8nTDD-OFplkVlW7Hii5hPw.png" /></figure><h3>Shifting</h3><p>The <strong>shift()</strong> method in Pandas is used to shift the time series values backwards and forwards. We will load the apple stock data again, set the <strong>Date </strong>column as an index and use only the <strong>Open</strong> &amp; <strong>Date</strong> columns for simplicity in this section.</p><blockquote>Input</blockquote><pre>df2 = pd.read_csv(‘Your File Path /aapl.csv’, parse_dates=[‘Date’], index_col=’Date’, usecols=[‘Date’, ‘Open’])</pre><pre>df2.head()</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*aTata-e1diEmM2a3rKX-zw.png" /></figure><p>We will shift the data (<strong>Open</strong> column) by day one.</p><blockquote>Input</blockquote><pre>df2.shift(1)</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*5lgEPeZVO2iL9Ce1e4avhQ.png" /><figcaption>See the position of the NaN value in the data set</figcaption></figure><p>We will pass the <strong>-1</strong> to <strong>shift</strong> method if we want to move backwards by one day.</p><blockquote>Input</blockquote><pre>df2.shift(-1)</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*T5PLn7c9cxrnT2uYugGqHQ.png" /><figcaption>See the position of the NaN value in the data set</figcaption></figure><p>We will add a column called <strong>PreviousDay_openval</strong> and find the daily difference in price.</p><blockquote>Input</blockquote><pre>df2[‘PreviousDay_openval’] = df2.shift(1)</pre><pre>df2</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*ncOPnGfZug55VNilpbb7tA.png" /></figure><p>Now lets take the difference</p><blockquote>Input</blockquote><pre>df2[‘Price Change’] = df2[‘Open’] — df2[‘PreviousDay_openval’] # Taking a difference</pre><pre>df2</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*IwPeu2foJWgzaFKxXQfZVg.png" /></figure><h3>Time zones</h3><p>The <strong>tz_localize()</strong> method converts the<strong> Datetime index </strong>to a time zone aware Date time index.</p><p>Let’s convert the data frame index into US/Eastern.</p><pre>Input</pre><pre>df.tz_localize(tz=’US/Eastern’)</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*0RkqmjAcGK3kfew9dGI50g.png" /></figure><blockquote>Input</blockquote><pre>df.index = df.index.tz_localize(tz=’US/Eastern’)</pre><pre>df.index</pre><pre>df.head()</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*RJJERelQ8TWEmmcOnrezoA.png" /></figure><p>The <strong>tz_convert() </strong>method converts the <strong>tz-aware </strong>Datetime Index from one time zone to another. Let’s convert data frame into ‘America/Los_Angeles’ TimeZone.</p><blockquote>Input</blockquote><pre>df = df.tz_convert(‘America/Los_Angeles’)</pre><pre>df</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*CxBhVHO2UkMi2BG_K2Ya6A.png" /></figure><p>Notice the hours and minutes are not 3 hours behind compared to the Eastern Time zone.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1c9c9a20ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Grouping data in Pandas]]></title>
            <link>https://medium.com/@arsalan_zafar/grouping-data-in-pandas-ca2edaec5eda?source=rss-e6f60ae08b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca2edaec5eda</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Arsalan Zafar]]></dc:creator>
            <pubDate>Wed, 27 Apr 2022 18:59:27 GMT</pubDate>
            <atom:updated>2022-04-27T18:59:27.730Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KnLlZ25N_gqsCy4edRa5pA.jpeg" /><figcaption><a href="https://pixabay.com/service/license/">Pixabay License</a></figcaption></figure><h3>What are we going to learn today?</h3><p>In this article, we will learn the Pandas <strong>groupby, aggregate </strong>and <strong>pivot table</strong> methods. Pandas <strong>groupby</strong> is used to perform a split on the data and combine it back into groups. <strong>Aggregate</strong> is used to apply a function like mean, median, min, and max etc to the grouped data. For example, we want to find the average age of passengers by the Passenger class.</p><h3>Why is it important to learn?</h3><p>Typically after loading and preparing a data set, we want to categorize it and apply some aggregation methods to summarize the data. <strong>Groupby</strong> and <strong>aggregate</strong> methods in Pandas are considered to be simpler than using other query languages.</p><h3>How can we achieve today’s goal?</h3><ul><li>Grouping</li><li>Grouping and Aggregation</li><li>Pivot Table</li></ul><p>Let’s import the Pandas library.</p><blockquote>Input</blockquote><pre>import pandas as pd</pre><p>Let’s load the titanic data set. this data set was can be downloaded from <a href="https://www.kaggle.com/c/titanic/data">here</a>.</p><blockquote>Input</blockquote><pre>df = pd.read_csv(‘/content/drive/MyDrive/Article upload/dataset/titanic.csv’)</pre><p>Let’s review the first few rows of the data set.</p><blockquote>Input</blockquote><pre>df.head()</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sd9NTATq4rYR_XVhNVd0xQ.png" /></figure><h3>Grouping</h3><p>Let’s group the data set based on the <strong>P-class</strong> (Passenger class) column and assign it to a variable. We will achieve this using the <strong>groupby</strong> function in Pandas.</p><blockquote>Input</blockquote><pre>pclass_grouped = df.groupby(‘Pclass’)</pre><pre>pclass_grouped</pre><blockquote>Output</blockquote><pre>&lt;pandas.core.groupby.generic.DataFrameGroupBy object at 0x7f6108d8f090&gt;</pre><p>It returns a <strong>DataFrameGroupBy</strong> object and splits the column into the groups based on its unique values. But we can see it gave nothing as an output. The reason is an object was returned and we have to perform more operations on it to derive valuable information.</p><p>First, we will see its unique values in the <strong>P-Class</strong> column with Panda’s <strong>unique</strong> method.</p><blockquote>Input</blockquote><pre>df[‘Pclass’].unique()</pre><blockquote>Output</blockquote><pre>array([3, 2, 1, 5])</pre><p>If we want to see data related to the certain group in the <strong>P-Class </strong>column we will use the<strong> get_group()</strong> method.</p><blockquote>Input</blockquote><pre>pclass_grouped.get_group(3)</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sj5hwpjDbqEU_-bB_lL81A.png" /><figcaption>Output is cropped</figcaption></figure><p>Awesome! Instead of writing long filters and conditions, we can filter out data in fewer lines of code.</p><p>The total rows in the data set are 420, but here we got 217 rows related to <strong>P-Class</strong> 3.</p><p>If we want to find average age of each passenger class. We will apply the <strong>mean</strong> method on the <strong>Age</strong> column in the grouped object.</p><blockquote>Input</blockquote><pre>pclass_grouped[‘Age’].mean()</pre><blockquote>Output</blockquote><pre>Pclass<br>1    40.918367<br>2    28.777500<br>3    24.126395<br>5    38.500000<br>Name: Age, dtype: float64</pre><p>Let’s make things more exciting and create a grouped object with two columns <strong>P-Class</strong> and <strong>Sex</strong>.</p><blockquote>Input</blockquote><pre>grouped_obj = df.groupby([‘Pclass’, ‘Sex’])</pre><pre>grouped_obj</pre><blockquote>Output</blockquote><pre>&lt;pandas.core.groupby.generic.DataFrameGroupBy object at 0x7f6108d87e50&gt;</pre><p>Let’s find the average age by passenger class and the gender.</p><blockquote>Input</blockquote><pre>grouped_obj[‘Age’].mean()</pre><blockquote>Output</blockquote><pre>Pclass  Sex   <br>1       female    41.333333<br>        male      40.520000<br>2       female    24.376552<br>        male      30.940678<br>3       female    23.073400<br>        male      24.669175<br>5       male      38.500000<br>Name: Age, dtype: float64</pre><p>We can see that it returns a series in the output, which means we can use the <strong>loc</strong> function to narrow down data for one passenger class.</p><blockquote>Input</blockquote><pre>grouped_obj[‘Age’].mean().loc[1]</pre><blockquote>Output</blockquote><pre>Sex<br>female    41.333333<br>male      40.520000<br>Name: Age, dtype: float64</pre><h3>Grouping and Aggregation</h3><p>The <strong>agg()</strong> method is used for aggregation that computes all the aggregate at once.</p><p>We will use the same grouped object and compute different aggregate functions (mean, median, min, sum).</p><blockquote>Input</blockquote><pre>grouped_obj[‘Age’].agg([‘median’, ‘mean’, ‘min’, ‘max’])</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*bRYyJxBnXJh4FbwQrRZV2A.png" /></figure><h3>Pivot Table</h3><p>The pivot table takes column-wise data as input and groups the columns into a two-dimensional table that summarizes the data.</p><p>The pivot table gives a multidimensional version of <strong>groupby</strong> aggregation.</p><p>We can create a pivot table in pandas with the <strong>pivot_table() </strong>method. Note — By default, it computes the mean values.</p><blockquote>Input</blockquote><pre>df.pivot_table(‘Age’, index=’Sex’, columns=’Pclass’)</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*oCbiQDjA23RyDuYaLX-7CA.png" /></figure><p>Using the same grouped_obj with unstack function will return the same output as the pivot table.</p><blockquote>Input</blockquote><pre>grouped_obj[‘Age’].agg(‘mean’).unstack()</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*8r_OiDQg9qOFvrorEQv5uQ.png" /></figure><h3>Conclusion</h3><p>In this article, we have covered <strong>groupby, pivot table </strong>and <strong>aggregation </strong>in Pandas. Thank you for reading hope you found it helpful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca2edaec5eda" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dates and Time series in Pandas]]></title>
            <link>https://medium.com/@arsalan_zafar/dates-and-time-series-in-pandas-64d7c50e9949?source=rss-e6f60ae08b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/64d7c50e9949</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Arsalan Zafar]]></dc:creator>
            <pubDate>Wed, 09 Mar 2022 04:43:13 GMT</pubDate>
            <atom:updated>2022-03-10T16:25:10.280Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*u21Gro1jU1k2csFSUxP2SQ.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/geralt-9301/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=62739">Gerd Altmann</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=62739">Pixabay</a></figcaption></figure><h3>What are we going to learn today?</h3><p>Today we will learn to work with time-series data. In fields such as Weather forecasting, Health care, finance and economics, the data is generated with time stamps. This type of data is called ‘Time Series’ data. Time Series data can be generated at regular or irregular intervals.</p><h3>Why is it important to learn?</h3><p>Handling time series data is different from the data handling we have seen so far. Time series data has the context of days, weeks, years, hours, minutes and seconds, and it makes data analysis quite different. It is essential to learn Panda’s methods that help us analyze time-series data.</p><h3>How can we achieve today’s goal?</h3><p>Today’s learning plan is:</p><ul><li>Conversion to DateTime data type</li><li>Earliest and Latest dates</li><li>Filtering based on dates</li><li>Resampling</li></ul><p>Let’s import the Panda’s library.</p><blockquote>Input</blockquote><pre>import pandas as pd</pre><p>For today’s article, we use the <strong>Ethereum dataset</strong>. The data set can be downloaded from <a href="https://drive.google.com/drive/folders/1GtaLYmHsAbcRF6_tNgPZtQd4lJGC0zvn?usp=sharing">here</a>.</p><blockquote>Input</blockquote><pre>df = pd.read_csv(‘/Your File Path/ethereum.csv’)</pre><h3>Conversion to DateTime data type</h3><p>So far, we have worked with integer, float, and string (text) data types. Now we will see a new data type called <strong>datetime</strong>. This data type allows us to treat and perform operations on date and timestamps exclusively. Let’s review the first few rows of the data set.</p><blockquote>Input</blockquote><pre>df.head(50)</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OZW909w31HOUuBbVZsIh2Q.png" /><figcaption>Output is cropped</figcaption></figure><p>We have a column labelled as <strong>Date</strong>, and it looks legit. But looks can be deceiving, so let’s run the <strong>info()</strong> method to confirm data types.</p><blockquote>Input</blockquote><pre>df.info()</pre><blockquote>Output</blockquote><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 23674 entries, 0 to 23673<br>Data columns (total 7 columns):<br> #   Column  Non-Null Count  Dtype  <br>---  ------  --------------  -----  <br> 0   Date    23674 non-null  object <br> 1   Symbol  23674 non-null  object <br> 2   Open    23674 non-null  float64<br> 3   High    23674 non-null  float64<br> 4   Low     23674 non-null  float64<br> 5   Close   23674 non-null  float64<br> 6   Volume  23674 non-null  float64<br>dtypes: float64(5), object(2)<br>memory usage: 1.3+ MB</pre><p>To convert the <strong>Date</strong> column into a <strong>datetime</strong> data type, we will use the <strong>to_datetime</strong> method. In addition, we will specify the format in which the date and time are stored in the <strong>Date</strong> column.</p><blockquote>Input</blockquote><pre>df[‘Date’] = pd.to_datetime(df[‘Date’], format=’%Y-%m-%d %I-%p’)</pre><p>%Y = Four digit year</p><p>%m = two digit month</p><p>%d = two digit day</p><p>%I-%p = 12 hour clock</p><p>Now, Let’s check the datatype of columns with the <strong>info()</strong> method.</p><blockquote>Input</blockquote><pre>df.info()</pre><blockquote>Output</blockquote><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 23674 entries, 0 to 23673<br>Data columns (total 7 columns):<br> #   Column  Non-Null Count  Dtype         <br>---  ------  --------------  -----         <br> 0   Date    23674 non-null  datetime64[ns]<br> 1   Symbol  23674 non-null  object        <br> 2   Open    23674 non-null  float64       <br> 3   High    23674 non-null  float64       <br> 4   Low     23674 non-null  float64       <br> 5   Close   23674 non-null  float64       <br> 6   Volume  23674 non-null  float64       <br>dtypes: datetime64[ns](1), float64(5), object(1)<br>memory usage: 1.3+ MB</pre><p>As expected, we will see the datatype of the <strong>Date </strong>column is now <strong>datetime</strong>.</p><p>We can use the <strong>loc</strong> method to call a specific element of the <strong>Date</strong> column by its day name using the <strong>day_name()</strong> method.</p><blockquote>Input</blockquote><pre>df.loc[0, ‘Date’].day_name()</pre><blockquote>Output</blockquote><pre>Friday</pre><p>Now let’s apply the <strong>day_name() </strong>to the entire Date column. We will use the <strong>dt</strong> class, which is used for the<strong> datetime</strong> properties like <strong>day_name()</strong> in a Series.</p><blockquote>Input</blockquote><pre>df[‘Date’].dt.day_name()</pre><blockquote>Output</blockquote><pre>0          Friday<br>1          Friday<br>2          Friday<br>3          Friday<br>4          Friday<br>           ...   <br>23669    Saturday<br>23670    Saturday<br>23671    Saturday<br>23672    Saturday<br>23673    Saturday<br>Name: Date, Length: 23674, dtype: object</pre><p>It returns the day’s name of each date of the Date column.</p><h3>Earliest and Latest Dates</h3><p>To see the latest and earliest date in the Date column, we will use the <strong>min() </strong>and <strong>max()</strong> methods.</p><p>The <strong>min()</strong> is to find the earliest dates and the <strong>max()</strong> is for the latest.</p><blockquote>Input</blockquote><pre>df[‘Date’].min()</pre><blockquote>Output</blockquote><pre>Timestamp(&#39;2017-07-01 11:00:00&#39;)</pre><blockquote>Input</blockquote><pre>df[‘Date’].max()</pre><blockquote>Output</blockquote><pre>Timestamp(&#39;2020-03-13 20:00:00&#39;)</pre><p>We can determine the total number of days by taking a difference between the latest and early dates.</p><blockquote>Input</blockquote><pre>df[‘Date’].max() — df[‘Date’].min()</pre><blockquote>Output</blockquote><pre>Timedelta(&#39;986 days 09:00:00&#39;)</pre><h3>Filtering based on dates</h3><p>The <strong>datetime</strong> data type supports filtering data with the context of time. For example, we want to see the data for the year 2020.</p><p>First, we will write a condition to select data greater than and then apply this condition to the data frame using the <strong>loc </strong>method.</p><blockquote>Input</blockquote><pre>filt = (df[‘Date’] &gt; ‘2020’)</pre><pre>df.loc[filt]</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BcYmVlTCzZGsmoQtqBVp9w.png" /><figcaption>Shows the data from year 2020</figcaption></figure><p>We can also set the <strong>Date</strong> column as an index with the same <strong>set_index</strong> method.</p><blockquote>Input</blockquote><pre>df.set_index(‘Date’, inplace=True)</pre><p>Let’s take a slice of the last six months of 2019.</p><blockquote>Input</blockquote><pre>df.loc[‘2019–06–01’:’2019–12–01&#39;]</pre><blockquote>Output</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2T_I6HoFwzWd1v4invu31Q.png" /></figure><h3>Resampling</h3><p>Resampling is a way to change the frequency of time-series data. For example, we want to convert the daily frequency to weekly or monthly frequency data.</p><p>The <strong>resample()</strong> method is used to resample the data in pandas. The <strong>resample(freq)</strong> is a class called <strong>“DatetimeIndexResampler”</strong>, which groups data in a <strong>Series</strong> object with regular time intervals. One thing to remember is we always use an <strong>aggregate</strong> function with the <strong>resample</strong> method.</p><p>Let’s resample the data by <strong>month</strong> <strong>(‘M’)</strong> and take its <strong>mean</strong> (aggregate method).</p><blockquote>Input</blockquote><pre>df.resample(‘M’)</pre><blockquote>Output</blockquote><pre>&lt;pandas.core.resample.DatetimeIndexResampler object at 0x7ff814d0f550&gt;</pre><blockquote>Input</blockquote><pre>df.resample(‘M’).mean()</pre><blockquote>Output</blockquote><p>Our data is resampled by month and shows every column mean by month.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*svcCGalSraazMqIvplPooQ.png" /><figcaption>Data is cropped</figcaption></figure><p>We can use the <strong>agg</strong> method with resample method. The <strong>agg</strong> method takes multiple aggregation functions and computes them simultaneously. Let’s resample our data by <strong>week (‘W) </strong>and with the <strong>min, max, and mean</strong>.</p><p>In the following code, we resample our data by <strong>week</strong> and take minimum value of the <strong>Close</strong> column, maximum value of the <strong>High</strong> column and mean of the <strong>Volume</strong> column.</p><blockquote>Input</blockquote><pre>df.resample(‘W’).agg({‘Close’: ‘min’, ‘High’: ‘max’, ‘Volume’:’mean’}).head(5)</pre><blockquote>Output</blockquote><p>The output shows, data is resampled by <strong>week</strong> and gives the <strong>min, max</strong> and <strong>mean</strong> of respective columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*XapBhwULdTmQzvqmO2kcsA.png" /></figure><h3>Conclusion</h3><p>In this article, we learned dates and time series in pandas. I hope it helps you thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64d7c50e9949" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>