<?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 Ganesh Dhasade on Medium]]></title>
        <description><![CDATA[Stories by Ganesh Dhasade on Medium]]></description>
        <link>https://medium.com/@g-dhasade16?source=rss-8bc856b7f34c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uJ0dYBbjUZ9EktrRWKswNA.jpeg</url>
            <title>Stories by Ganesh Dhasade on Medium</title>
            <link>https://medium.com/@g-dhasade16?source=rss-8bc856b7f34c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 15 Nov 2026 12:56:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@g-dhasade16/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[Year-Over-Year Growth]]></title>
            <link>https://medium.com/swlh/year-over-year-growth-28c428f74060?source=rss-8bc856b7f34c------2</link>
            <guid isPermaLink="false">https://medium.com/p/28c428f74060</guid>
            <category><![CDATA[business]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[kpi]]></category>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Ganesh Dhasade]]></dc:creator>
            <pubDate>Mon, 03 Jul 2023 23:19:19 GMT</pubDate>
            <atom:updated>2023-07-03T23:19:19.535Z</atom:updated>
            <content:encoded><![CDATA[<p>What it is, how to calculate it, significance in small and large businesses, with examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f_aY2LYeV9FsHMxi1M1xMg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/fr/@morganhousel?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Morgan Housel</a> on <a href="https://unsplash.com/photos/PcDGGex9-jA?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Introduction:</h3><p>Year-Over-Year growth — referred to as Year-on-Year or YoY growth, is a fundamental metric business use to assess their performance and track progress over time. YoY metric provides valuable insights into the rate at which a business expands or contracts, enabling stakeholders to make informed decisions. It can measure the performance of products, services, and so on.</p><p>In this blog, I aim to define year-over-year growth, explain its calculation formula, highlights its significance for both small and large businesses and finally discuss its advantages and disadvantage.</p><h3>What is Year-over-Year Growth?</h3><p>Year-over-Year growth is a fundamental metric used to measure the percentage change in a particular variable, such as revenue, profit, sales, or customer base, over a year-long period. Basically, it compares data from the current year with data from the same period in the previous year to determine the rate of growth.</p><p><strong>For example:</strong> If the company’s revenue was £1 million in 2021 and £2 million in 2022, the year-over-year growth rate would be 100%.</p><h3>Formula to Calculate Year-over-Year Growth:</h3><pre>Year-over-Year Growth = (<br>                          (Current Year Data - Previous Year Data) / <br>                           Previous Year Data<br>                        ) * 100</pre><p><strong>For example: </strong>Let’s consider a small business that recorded £70,000 in revenue in sales in 2021 and £100,000 in revenue in sales in 2022.</p><p><strong>Year-over-Year Growth</strong> = ( (£100,000 - £70,000) / £70,000) ) * 100 = 42.86%</p><h3><strong>Importance for Small and Large Businesses:</strong></h3><p>Year-over-Year growth is a crucial metric for businesses of all sizes, and its significance can be observed through the following examples:</p><ol><li><strong>Small Business:</strong></li></ol><p>A local bakery experiencing consistent year-over-year growth in revenue can determine the effectiveness of its marketing campaigns, pricing strategies, and customer satisfaction initiatives.</p><p>By analyzing the year-over-year growth rate, the bakery can make data-driven decisions, such as expanding its product line, hiring additional staff, or investing in marketing channels that have yielded the highest returns.</p><p>Also for small businesses YoY growth rate plays an important role when businesses need to raise investment from investors in order to grow or expand.</p><p>2.<strong> Large Business:</strong></p><p>A multinational technology and service-based company with operations in multiple countries can utilize YoY growth to access the performance of different segments, regions or markets.</p><p>By comparing YoY growth rates, the company can identify markets with the highest potential and allocate resources accordingly.</p><p>Moreover, investors and stakeholders rely on YoY growth to evaluate the company’s overall financial health and potential for future profitability.</p><h3>Advantages of Year-over-Year Growth:</h3><ol><li><strong>Long-term Performance Assessment: </strong>YoY growth allows business to evaluate their performance over an extended period, enabling them to identify trends, patterns, and potential areas for improvement or investment.</li><li><strong>Benchmarking:</strong> Businesses can assess their market performance by comparing YoY growth rates to industry standards or competitors.</li><li><strong>Goal Setting and Forecasting: </strong>YoY growth data provides a foundation for setting realistic growth targets and developing strategic plans.</li></ol><h3>Disadvantages of Year-over-Year Growth:</h3><ol><li><strong>Limited Context: </strong>YoY growth provides a snapshot of performance without accounting the external factor, such as economic fluctuations or market dynamics, which may impact the result. <br>For example, Many tech companies saw revenue growth during covid, and they invested heavily in employing and adapting new technology. However, the duration of the covid and other external circumstances such as war and inflation force corporations to reduce cash burn in the form of layoffs, suspend projects, stop new hiring and so on.</li><li><strong>Incomplete Picture: </strong>Focusing solely on YoY growth may obscure short-term fluctuations, preventing organisations from discovering underlying difficulties or opportunities.</li><li><strong>Data Quality:</strong> YoY growth is only as reliable as the accuracy and consistency of the data used for calculations. Inaccurate or incomplete data can lead to misleading conclusions. <br>Personally, I believe that if there is any data quality issue available in data, it may bring serious consequences to the decisions. Hence, data quality must be taken seriously.</li></ol><h3><strong>Conclusion:</strong></h3><p>Year-over-Year growth is a valuable metric that enables businesses to track their progress, make informed decisions, and assess their performance over time. By understanding the definition, calculation formula and significance of this metric, both small and large business can leverage year-over-year growth to enhance their strategic planning.</p><p>As previously said, YoY growth rates provide several advantages; nevertheless, prior to making any strategic decisions, it is important to consider the drawbacks as well to avoid future consequences.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28c428f74060" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/year-over-year-growth-28c428f74060">Year-Over-Year Growth</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL — SubQuery vs CTEs]]></title>
            <link>https://g-dhasade16.medium.com/sql-subquery-vs-ctes-b312a64614f?source=rss-8bc856b7f34c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b312a64614f</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-modeling]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Ganesh Dhasade]]></dc:creator>
            <pubDate>Sun, 02 Jul 2023 16:09:36 GMT</pubDate>
            <atom:updated>2023-07-02T16:09:36.436Z</atom:updated>
            <content:encoded><![CDATA[<h3>SQL — SubQuery vs CTEs</h3><p>Differences, examples on SubQuery vs Common Table Expressions (CTE)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*akaZCEWu-YERVMty5Jd1Fw.jpeg" /><figcaption>Image by Author</figcaption></figure><p>In SQL, both Subqueries and Common Table Expressions (CTEs) are used to perform complex queries or manipulate data. However differences in terms of syntax and usage.</p><p>First, let&#39;s explore each Subquery and CTEs with examples.</p><ol><li><strong>SubQueries:</strong></li></ol><p>Subquery, also known as a nested query, is a query nested within another query. It allows you to retrieve data based on the results of another query.</p><p>Subqueries can be used in various parts of SQL statements, such as the SELECT ,FROM ,WHERE orJOIN clauses. Here’s an example:</p><pre>SELECT <br>    employee_id,  <br>    total_sales<br>FROM <br>    (SELECT <br>        employee_id, <br>        SUM(sales_amount) AS total_sales<br>    FROM <br>        sales<br>    GROUP BY <br>        employee_id<br>    )<br>WHERE <br>    total_sales &gt; 10000</pre><p>In the above example, <strong><em>(SELECT employee_id, SUM(sales_amount) AS total_sales FROM sales GROUP BY employee_id) </em></strong>calculate’s total_sales amount done by each employee. The outer query then retrieves the employee IDs and total sales of employees who generated above 10,000 in sales.</p><p>Subqueries are beneficial when you need to <strong><em>filter or retrieve data</em></strong> based on the results of another query. They can be used to perform calculations, filtering or joining operations within a <strong>single SQL</strong> statement.</p><p>2. <strong>Common Table Expressions (CTEs):</strong></p><p>CTE is a temporary named result set that you can reference within a SQL statement. It allows you to break down complex queries into smaller, more manageable parts.</p><p>CTEs are defined using the WITH keyword and can be used in subsequent queries just like regular tables. Here’s an example:</p><pre>WITH employee_sales AS <br>(<br>    SELECT <br>        employee_id, <br>        SUM(sales_amount) AS total_sales<br>    FROM <br>        sales<br>    GROUP BY <br>        employee_id<br>)<br>SELECT <br>    employee_id, <br>    total_sales<br>FROM <br>    employee_sales<br>WHERE <br>    total_sales &gt; 10000</pre><p>In the above example, employee_sales is defined, which calculates the total sales for each employee from the sales table. Then, the main query references the employee_sales CTE and retrieves the employee IDs and total sales of employees who generated above 10,000 in sales.</p><p>CTEs are particularly useful when you need to <strong><em>reuse the same result set</em></strong> multiple times within the query or when you want <strong><em>to simplify complex queries</em></strong> by dividing them into logical parts.</p><p><strong>Conclusion:</strong></p><p>Subqueries and CTEs serve a similar purpose as you can see in the above examples, but differ in syntax and usage.</p><p>CTEs are defined using WITH keyword and can be referenced multiple times in a query, while Subqueries are nested queries used within other queries. Both techniques are powerful and can help you write complex SQL queries efficiently.</p><p>In the actual world, several tables must be combined to form a single data model. In a single data model, performed calculations are referred to several times. Subqueries and CTEs both aid in the efficient writing of queries. Personally, I like CTEs because they make queries easier to write and more readable.</p><p>I hope this blog is helpful for you and hopefully, it helps to understand the difference between Subqueries and CTEs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b312a64614f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Install Python into Mac / Windows / Linux Machine]]></title>
            <link>https://faun.pub/1-install-python-into-mac-windows-linux-machine-84a51af0bf9b?source=rss-8bc856b7f34c------2</link>
            <guid isPermaLink="false">https://medium.com/p/84a51af0bf9b</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ganesh Dhasade]]></dc:creator>
            <pubDate>Mon, 20 Jun 2022 22:53:54 GMT</pubDate>
            <atom:updated>2022-06-30T12:03:37.991Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*caTlEJc6bbFvbbs6MPvShg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@hiteshchoudhary">Hitesh Choudhary</a> | <a href="https://unsplash.com/s/photos/coding">Unsplash</a></figcaption></figure><p><strong>Introduction:</strong></p><p>In this blog I cover all steps required to install Python into your Mac or Windows or Linux machine. At the end of this blog you will be ready to start and explore the Python programming world.</p><ol><li><strong>Python on Mac</strong></li></ol><p>Since macOS version 10.8 it comes with Python 2.7 pre-installed by Apple. Which you can upgrade or install by following below simple steps below.</p><p><strong>i. Check which Python version pre-installed into your mac.</strong></p><ul><li>Press cmd+space_bar on keyboard &amp; search for terminal.app to open terminal.</li><li>Type command python --version to check current version of python.<br>You will see the pre-installed Python version 2.7.</li><li>Now type python3 --version to check python3 available in the system, <br>if it <strong><em>throw error</em> </strong>means version 3 is not available or <br>if it <strong><em>give output</em></strong> like Python 3.0 means mac already have Python version 3.</li></ul><p><strong>ii. To install Python version 3 into mac.</strong></p><ul><li>Go to browser and search <a href="https://medium.com/www.python.org">www.python.org</a> and then click on download tab or click this <a href="https://www.python.org/downloads/">Python download link</a>.</li><li>Download latest version of Python for <strong>macOS</strong>.</li><li>Double click (open installed file) and follow normal installation steps.</li><li>At end you will get message Congratuation! Python 3.10.5 for macOS or later was successfully installed.</li><li>Close the installation window &amp; move downloaded file to bin.</li></ul><p><strong>iii. Check Python3 Installation successful or not.</strong></p><ul><li>Same as above open terminal.app &amp; type python3 --version</li><li>You will get output as Python with installed version number.</li><li>If you still get an error restart the terminal and run same command to check installed version.</li><li>Still got an error then again follow step 2.</li></ul><p><strong>2. Python on Windows Machine</strong></p><p>Windows Machine not come with pre-installed Python. To install Python on Windows machine follow below steps.</p><p><strong>i. Install Python3</strong></p><ul><li>Go to browser and search <a href="https://medium.com/www.python.org">www.python.org</a> and then click on download tab or click this <a href="https://www.python.org/downloads/">Python download link</a>.</li><li>Download latest version of Python for <strong>Windows</strong>.</li><li>Double click (open installed file) and follow normal installation steps.</li><li>Please follow below necessary steps to have proper installation.</li><li><em>First window </em>— Check both option i.e. <br>Install Launcher for all users (recommended) &amp;<br>Add Python 3.5 to path (to avoid further manual steps to add python environment path)</li><li><em>Second window</em> — Check below recommended options<br>Install for all users<br>Associate files with Python (requires the py launcher)<br>Create Shortcuts for installed applications<br>Add Python to environment variables<br>Precompile standard library</li><li>Click to install.</li><li><em>End window</em> — display message Setup was successful — now close this window.</li></ul><p><strong>ii. Check installation successful or not.</strong></p><p>You can check python installation by 2 option</p><p><strong>a. Using Python IDLE </strong>i.e. Python Integrated Development and Learning Environment.</p><ul><li>Click on windows icon and search for Python IDE &amp; press enter.</li><li>Run command python --version it will display an output with Python and its installed version number.</li></ul><p><strong>b. Using cmd </strong>i.e. Windows Command Prompt</p><ul><li>Click on windows icon &amp; search for cmd &amp; press enter.</li><li>Run command python this will open same shell as Python IDLE. If it throws means Python not present in your system path.</li><li>To set Python into system path.<br>Click on windows icon and search Environment Variables<br>Click on Edit the system environment variables <br>Click on Environment Variables <br>Select Path and Edit <br>Add Python installed directory path along with add ; semicolon at end of path.</li><li>Now open windows cmd and search python if path added correctly it will open Python IDLE type shell.</li><li>Run command python --version this will display installed Python version.</li></ul><p><strong>3. Install Python on Linux or Ubuntu</strong></p><p>Mostly Python not pre-installed into Linux or Ubuntu. To install Python follow below steps.</p><p><strong>i. Install Python3</strong></p><ul><li>Press super_key or windows key &amp; search terminal &amp; press enter.</li><li>To install write command sudo apt install python3 <br>It will prompt password enter password to proceed with installation.</li><li>Once above installation done, install other essential packages like pip, build essential, dev and so on. <br>To install all packages in one command run command sudo apt install python3-pip build essential python3-dev</li><li>Python has been installed successfully to you Linux or Ubuntu machine.</li></ul><p><strong>ii. Check Python installation successful or not.</strong></p><ul><li>On the above same terminal screen type python3 -V to check current version of python.<br>You will see the output with Python and its installed version number.</li></ul><p><strong>Conclusion:</strong></p><p>In this blog, I tried to cover all steps required to install Python into your Mac or Windows or Linux Machine.</p><p>I hope you like this blog, feel free to join me on <a href="https://www.linkedin.com/in/ganesh-dhasade-099b4a94/">LinkedIn</a>. I love to know your thoughts on this article and feedback.</p><p>Thank you for reading.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*FajOmowapY_oBIlq.png" /></figure><h4>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author 👇</h4><h4>🚀Developers: Learn and grow by keeping up with what matters, <a href="https://faun.to/8zxxd">JOIN FAUN.</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84a51af0bf9b" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/1-install-python-into-mac-windows-linux-machine-84a51af0bf9b">Install Python into Mac / Windows / Linux Machine</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Window Functions — Part 2]]></title>
            <link>https://medium.com/data-science/sql-window-functions-part-2-bbdcd16c1ff7?source=rss-8bc856b7f34c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbdcd16c1ff7</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ganesh Dhasade]]></dc:creator>
            <pubDate>Fri, 13 Nov 2020 00:30:18 GMT</pubDate>
            <atom:updated>2020-11-13T18:41:20.267Z</atom:updated>
            <content:encoded><![CDATA[<h3>SQL Window Functions — Part 2</h3><h4>Different Types Of SQL Windows Functions.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*u9pGRivjh534RbQF" /><figcaption>Photo by: <a href="https://unsplash.com/@franki">Franki</a> | <a href="https://unsplash.com/">Unsplash.com</a></figcaption></figure><p><strong>Introduction:</strong></p><p>A Window Function performs a Data Analysis calculation across a set of table rows that are somehow related to the current row. Address the comparable type of calculation can be done with an aggregate function that gives a single row or grouped by condition (refer to Figure 1).</p><p>Window function does not cause rows to become grouped into a single output row. Rows retain their separate identities also able to access more than just the current row of the query result. (refer to Figure 1).</p><pre><strong>Window Function Syntax:</strong><br>Window_Function([All] expression) <br>OVER( [PARTITION BY expression_list] [ORDER BY order_list Row_or_ Range clause] )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JJpNcDN88_wlGz9W.png" /><figcaption>Figure 1 — Difference between — Aggregated and Windows function</figcaption></figure><p>For more information please visit my last blog, I<a href="https://medium.com/analytics-vidhya/sql-windows-function-5dc5cbdb1aa"> Introduced the SQL Window Function-Part I</a> and gave an overview of different types of SQL Window Functions.</p><p>In this blog, I am explaining all three major types of SQL Window Function along with examples.</p><p>The database used to explain the below concepts: Postgres database.</p><p>Dataset: Available at Github: <a href="https://github.com/GDhasade/Medium.com_Contents/blob/master/SQL/Retails.csv">Retails.csv</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VMpm2f9Q763ulJwkSf0NOQ.png" /><figcaption>Retails Table Screenshot.</figcaption></figure><p><strong>Types of SQL Window Functions:</strong></p><ol><li><strong>Window Aggregated Function</strong></li><li><strong>Window Ranking Aggregated Function</strong></li><li><strong>Window Analytical Function</strong></li></ol><h3><strong>1. Window Aggregated Function</strong></h3><p>Consist one of the supporting aggregated function i.e. AVG(), COUNT(), MIN(), MAX(), SUM().</p><p><strong>a. AVG():</strong></p><ul><li>Returns average value for the input expression values.</li><li>The function works with Numeric Values and ignores NULL values.</li></ul><p><strong>Example:</strong></p><p>Write a query to calculate the average order price.</p><pre><strong>Query:<br></strong>SELECT order_id, product_id, price, AVG(price) OVER (PARTITION BY order_id) AS Average_Order_Price <br>FROM retails</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*MEAhFUEwSBH82Uw-J8n5uA.png" /><figcaption>Output — Query — AVG()</figcaption></figure><p><strong>Explanation:</strong></p><ul><li>To calculate average order price, window function used AVG() on price columns and partition by on order_id</li><li>Consider order id: 1112 — consist 3 products (i.e. 1,2,5). The average value of those 3 products are (866 + 163 +173) / 3 = 400.667</li></ul><p><strong>b. COUNT():</strong></p><ul><li>Calculates the number of rows with NULL values too if available in column or expression.</li><li>This window function is helpful while creating a new feature in the dataset. Like count number of entries belong to each customer.</li></ul><p><strong>Example:</strong></p><p><strong>Query 1:</strong> Calculate the number of products purchased by a customer in the order.</p><pre>SELECT order_id, name, product_id, COUNT(*) OVER (Partition BY order_id) AS Number_of_Products <br>FROM retails</pre><p><strong>Query 2:</strong> Calculate the number of product sales purchased (running total) by the customer.</p><pre>SELECT order_id, name, product_id, COUNT(*) OVER (Order BY order_id) AS Number_of_Products <br>FROM retails</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9AohJxnCXcseOU70wJU2Eg.png" /><figcaption>Output — Query 1 &amp; 2 — COUNT()</figcaption></figure><p><strong>Explanation:</strong></p><p><strong>Query 1:</strong></p><ul><li>Partition by order_id counts number of records belongs to particular order_id.</li><li>In the output, we can see several products for each order displayed.</li></ul><p><strong>Query 2:</strong></p><ul><li>Order by order_id counts a number of records and particular order_id and then add number records of consecutive order.</li><li>Output: We can see the count is increased by the number of records related to particular order_id.</li></ul><p><strong>c. Min() or Max():</strong></p><ul><li>Min() or Max() return Minimum or Maximum value of the expression across the input values respectively.</li><li>Both window function works with Numeric values and ignores NULL values.</li></ul><p><strong>Example:</strong></p><p>Below query add a new feature into the result set, Minumum and Maximum price of the product purchased in respective order.</p><pre><strong>Query:</strong><br>SELECT order_id, name, product_id, price, <br>MIN(price) OVER (Partition BY order_id) AS Minimum_Price_Product,<br>MAX(price) OVER (Partition BY order_id) AS Maximum_Price_Product <br>FROM retails</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l_nlyO2qjWZU5gG4K9wy3g.png" /><figcaption>Output- Query- MIN() or MAX()</figcaption></figure><p><strong>Explanation:</strong></p><ul><li>For each order_id record respective minimum and maximum price of the product has been added.</li><li>We can use each function separately too.</li></ul><p><strong>d. Sum():</strong></p><ul><li>Returns sum/total expression across all input value.</li><li>The function works with Numeric Values and ignores NULL values.</li></ul><p><strong>Example:</strong></p><p>Below query return Total Price of each order_id.</p><pre><strong>Query:</strong><br>SELECT order_id, name, product_id, price, <br>SUM(price) OVER (PARTITION BY order_id) AS Average_Order_Price <br>FROM retails</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*U1kRoZsWS3ZacS4umxUwrg.png" /><figcaption>Output — Query — SUM()</figcaption></figure><p><strong>Explanation:</strong></p><ul><li>New column added with total_order_price for each order_id.</li><li>Helpful to analyse data, where we have a number of records, belongs to each order_id.</li></ul><h3>2. <strong>Window Ranking Aggregated Function:</strong></h3><p>Consist one of the supporting ranking function i.e. RANK(), DENSE_RANK(), ROW_NUMBER().</p><p><strong>a. RANK():</strong></p><ul><li>The Rank of a value in a group of values based on the <strong>ORDER BY</strong> expression in the OVER clause (refer Query 1).</li><li>Each value is ranked within its <strong>PARTITION BY</strong> expression (refer Query 2).</li><li>Rows with equal values for the ranking criteria receive the same rank.</li><li>Tie or same rank skip the consecutive rank eg. Rank (): 1,1,3,4,5.</li></ul><p><strong>Example:</strong></p><p><strong>Query 1:</strong> Rank the product based on their prices.</p><pre>SELECT order_id, name, product_id, price, <br>RANK() OVER (ORDER BY price) AS Rank_Product_Price <br>FROM retails</pre><p><strong>Query 2:</strong> Rank the product based on their prices in each order (i.e. partition by order_id).</p><pre>SELECT order_id, name, product_id, price, <br>RANK() OVER (PARTITION BY order_id ORDER BY price) AS Rank_Product_Price <br>FROM retails</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CLwvDwN84aMn53ORvKkzLg.png" /><figcaption>Output — Query 1 &amp; 2 — RANK()</figcaption></figure><p><strong>Explanation:</strong></p><p>As we can see in both query, ORDER BY states the expression used to rank the values.</p><p><strong>Query 1:</strong></p><ul><li>The ranking is done based on product_price.</li><li>Also note, 9 rows with the same value has tie rank 1.</li><li>So next Rank value starts with 10.</li></ul><p><strong>Query 2:</strong></p><ul><li>Rank has been done by ORDER BY expression i.e. price column.</li><li>Check order_id 114, we can see the rank for first 2 product prices are same. Hence rank assign to it is 1.</li><li>Next product price rank with 3 within that order_id.</li></ul><p><strong>b. DENSE_RANK():</strong></p><ul><li>Similarly to Rank() function, Rank of a value in a group of values based on the <strong>ORDER BY</strong> expression and the OVER clause and each value is ranked within its <strong>PARTITION BY </strong>expression.</li><li>The difference is, Rows with equal values receive the same rank and Tie or the same rank not skip the consecutive rank.</li><li><em>Example:</em> Dense_Rank(): 1,1,2,3,4</li></ul><p><strong>EXAMPLE:</strong></p><p><strong>Query:</strong> Dense_Rank the product based on their prices in each order (i.e. partition by order_id).</p><pre>SELECT order_id, name, product_id, price, <br>DENSE_RANK() OVER (PARTITION BY order_id ORDER BY price) AS Dense_Rank_Product_Price <br>FROM retails</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PCCZg9PKjx8OEMBHlxl_XQ.png" /><figcaption>Output — Query — Dense_Rank()</figcaption></figure><p><strong>Explanation:</strong></p><ul><li>As we can see ranking to each row done based on ORDER BY expression i.e. price values also within each order_id i.e. (PARTITION BY order_id).</li><li>order_id 1114, have 5 products out of which 2 products having the same price hence rank tie i.e. 1.</li><li>The next rank starts with 2 (this is the major difference between Rank() and Desne_Rank() function).</li><li>Dense_Rank() not skip the consecutive rank number.</li></ul><p><strong>c. CUME_DIST():</strong></p><ul><li>Calculates<strong> </strong>Relative Rank of the current row within a window partition based on below <strong>Formula:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z1grFEn70Qxmmt1sZXZh5Q.png" /></figure><p><strong>EXAMPLE:</strong></p><p><strong>Query:</strong> CUME_DIST i.e. Relative rank the product based on their prices in each order (i.e. partition by order_id).</p><pre>SELECT order_id, name, product_id, price, <br>CUME_DIST() OVER (PARTITION BY order_id ORDER BY price) AS Dense_Rank_Product_Price <br>FROM retails</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FcLvftJcnU5I8UCIg_YNcg.png" /><figcaption>Output — Query — CUME_DIST() i.e. Relative Rank</figcaption></figure><p><strong>Explanation:</strong></p><p>Let&#39;s consider order_id 1112 having 3 products, relative rank calculated as discussed below formula used:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z1grFEn70Qxmmt1sZXZh5Q.png" /></figure><ul><li>Row no. 3— First product: 1/3 = 0.3333</li><li>Row no. 4— Second product: 2/3 = 0.666</li><li>Row no. 5— Third product: 3/3 = 1</li></ul><p>Similarly, if product having same value or price then relative rank also same check order_id 1114 in output screenshot.</p><p><strong>d. ROW_NUMBER():</strong></p><ul><li>An ordinal number of the current row within its partition based on <strong>ORDER BY</strong> expression in the OVER clause.</li><li>Each value is ordered within its <strong>PARTITION BY</strong> expression.</li><li>Rows with equal values for the ORDER BY expressions receive different row numbers non deterministically.</li></ul><p><strong>EXAMPLE:</strong></p><p><strong>Query:</strong> Assign Row_Number to the product based on their prices in each order (i.e. partition by order_id).</p><pre>SELECT order_id, name, product_id, price, <br>ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY price) AS Row_Number_Product_Price <br>FROM retails</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QlecNTNbEY2QF-D6Q0m3rA.png" /><figcaption>Output — Query — Row_Number()</figcaption></figure><p><strong>Explanation:</strong></p><ul><li>As we can see in output screenshot, row number assign based on price (ORDER BY expression) within each order (PARTITION BY order_id).</li><li>Not consider value same or not, just assign row_number to each row in the expression.</li></ul><p><strong>e. NTILE():</strong></p><ul><li>Divides the rows for each window partition, as equally as possible, into a specified number of ranked groups.</li><li><strong><em>Requires</em></strong> ORDER BY clause in the OVER clause.</li><li>The column or expression specified in ORDER BY clause, first all values has been sorted in ascending order and then equally assign group number.</li></ul><p><strong>Example:</strong></p><p><strong>Query: </strong>Assign<strong> </strong>Group/cluster/bucket number to all row into 10 different groups based on the product price.</p><pre>SELECT order_id, name, product_id, price, <br>NTILE(10) OVER (ORDER BY price) AS NTile_Product_Price <br>FROM retails</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*QTZECW2zVXUspmEM3DBcEA.png" /><figcaption>Output — Query — NTILE()</figcaption></figure><p><strong>Explanation:</strong></p><ul><li>In this dataset, we have a total of 50 records.</li><li>Hence, each clustered consist of 5 rows as shown in the output screenshot.</li><li>First, all rows have been sorted with the price and then assign a group number to each row.</li></ul><p><strong>f. PERCENT_RANK()</strong></p><ul><li>Percentage rank of the current row using the following formula:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xtybJSKbatosqIjhXJsO1w.png" /></figure><p><strong>Example:</strong></p><p><strong>Query: </strong>Calculate or assign percentage rank to all row based on the product price.</p><pre>SELECT order_id, name, product_id, price, <br>PERCENT_RANK() OVER (PARTITION BY order_id ORDER BY price) AS Row_Number_Product_Price <br>FROM retails</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iTFvN8hrONOG0NTpwx3FVA.png" /><figcaption>Output — Query — Percent_Rank()</figcaption></figure><p><strong>Explanation:</strong></p><p>Let’s consider order_id 1114 having 5 products, relative rank calculated as discussed below formula used:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xtybJSKbatosqIjhXJsO1w.png" /></figure><ul><li>Row no. 9— First product: (1–1)/(5–1) = 0</li><li>Row no. 10— Second product: (1–1)/(5–1) = 0</li><li>Row no. 11— Third product: (3–1)/(5–1) = 0.5</li><li>Row no. 12 — Forth product: (4–1)/(5–1) = 0.75</li><li>Row no. 13 — Fifth product: (5–1)/(5–1) = 1</li></ul><h3><strong>3. Window Analytic Functions:</strong></h3><p>Consist one of the supporting ranking function i.e. LAG(), LEAD(), FIRST_VALUE(), LAST_VALUE().</p><p><strong>a. LAG() or LEAD():</strong></p><p><strong>Syntax:</strong></p><pre>LAG | LEAD (expression)<br>    OVER ([ PARTITION BY expression_list] [ORDER BY order_list] )</pre><ul><li>LAG or LEAD returns, value for the row value <strong><em>before</em></strong> or <strong><em>after</em></strong><em> </em>the current row in a partition respectively.</li><li>If no row exists, null is returned.</li></ul><p><strong>Example:</strong></p><p><strong>Query: </strong>Add new feature 1 step LAG or LEAD product price within each order (i.e. PARTITION BY order_id)</p><pre>SELECT order_id, name, product_id, price, <br>LAG(price,1) OVER (PARTITION BY order_id ORDER BY price) AS LAG_Product_Price,<br>LEAD(price,1) OVER (PARTITION BY order_id ORDER BY price) AS LEAD_Product_Price<br>FROM retails</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IezQeDXpe6ZNL2Ig3LL7DA.png" /><figcaption>Output — Query — LAG() or LEAD()</figcaption></figure><p><strong>Explanation:</strong></p><ul><li>As we can see both lag and lead column give 1 step value respectively within the partition of order_id.</li><li>When its first row in LAG() gets imputed with NULL.</li><li>Similarly, in LEAD() the last row gets imputed with NULL.</li></ul><p><strong>b. FIRST_VALUE() or LAST_VALUE():</strong></p><p><strong>Syntax:</strong></p><pre>FIRST_VALUE | LAST_VALUE ( expression ) <br>      OVER ( [PARTITION BY expression_list ] [ ORDER BY order_list ][ row_or_range_clause ] )</pre><ul><li>FIRST_VALUE or LAST_VALUE return First-row or Last-row value of the specified expression with respect to the window frame (partition) respectively.</li></ul><p><strong>Example:</strong></p><p><strong>Query: </strong>Add new feature FIRST_VALUE or LAST_VALUE product price within each order (i.e. PARTITION BY order_id).</p><pre>SELECT order_id, name, product_id, price, <br>FIRST_VALUE(price) OVER (PARTITION BY order_id) AS FIRST_VALUE_Product_Price,<br>LAST_VALUE(price) OVER (PARTITION BY order_id) AS LAST_VALUE_Product_Price<br>FROM retails</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x4NJVtpCpzrEfjtpOaLsbw.png" /><figcaption>Output — Query — First_Value() or Last_Value()</figcaption></figure><p><strong>Explanation:</strong></p><ul><li>As we can see both First_Value() and Last_Value() column give first-row value and last-row value respectively.</li></ul><p><strong>c. NTH_VALUE():</strong></p><p><strong>Syntax:</strong></p><pre>NTH_VALUE (expression, nth_value ) <br>      OVER ( [PARTITION BY expression_list ] [ ORDER BY order_list ][ row_or_range_clause ] )</pre><ul><li>NTH_VALUE return nth value assigned with expression with respect to the window frame (partition) respectively.</li><li>If nth_value is not available then its get imputed with NULL.</li></ul><p><strong>Example:</strong></p><p><strong>Query: </strong>Add new feature NTH_VALUE product price within each order (i.e. PARTITION BY order_id).</p><pre>SELECT order_id, name, product_id, price, <br>NTH_VALUE(price,3) OVER (PARTITION BY order_id) AS NTH_VALUE_Product_Price<br>FROM retails</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3B0SKUFGOcsWyN1EUh6SIQ.png" /><figcaption>Output — Query — NTH_VALUE()</figcaption></figure><p><strong>Explanation:</strong></p><ul><li>As in query we assigned nth_value as 3, it returns the 3rd-row value is partitioned by order_id.</li><li>For order_id 1111 there are only 2 products, hence column gets imputed with the NULL value.</li></ul><p><strong>Conclusion:</strong></p><p>In this blog, I tried to explain the major types of Window Function in SQL.</p><p>Window Functions are very useful while doing data analysis using SQL and easy to use.</p><p>Window Functions revolves around OVER, PARTITION BY and ROW or RANGE clauses.</p><p>I hope you like this blog, feel free to join me on <a href="https://www.linkedin.com/in/ganesh-dhasade-099b4a94/">LinkedIn</a>. I love to know your thoughts on this article and feedback.</p><p>Thank you for reading.</p><p><strong>Resources:</strong></p><p>Dataset and SQL scripts were available at <a href="https://github.com/GDhasade/Medium.com_Contents/tree/master/SQL">GITHUB</a>.</p><p><strong>References:</strong></p><ol><li>postgresql.org (2019). <em>PostgreSQL: Documentation: 9.1: Window Functions</em>. [online] Postgresql.org. Available at: <a href="https://www.postgresql.org/docs/9.1/tutorial-window.html.">https://www.postgresql.org/docs/9.1/tutorial-window.html.</a></li><li>drill.apache.org (n.d.). <em>SQL Window Functions Introduction — Apache Drill</em>. [online] drill.apache.org. Available at: <a href="https://drill.apache.org/docs/sql-window-functions-introduction/">https://drill.apache.org/docs/sql-window-functions-introduction/</a>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbdcd16c1ff7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/sql-window-functions-part-2-bbdcd16c1ff7">SQL Window Functions — Part 2</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Windows Function]]></title>
            <link>https://medium.com/analytics-vidhya/sql-windows-function-5dc5cbdb1aa?source=rss-8bc856b7f34c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dc5cbdb1aa</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Ganesh Dhasade]]></dc:creator>
            <pubDate>Tue, 10 Nov 2020 01:58:30 GMT</pubDate>
            <atom:updated>2020-11-11T12:46:41.347Z</atom:updated>
            <content:encoded><![CDATA[<h3>SQL Window Function — Part I</h3><h4>Introduction &amp; Overview Types of Window Function in SQL.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B4YyrDuWYuUvFW3j9yqmyA.png" /><figcaption>Image by Author, inspired by the <a href="https://www.toptal.com/sql/intro-to-sql-windows-functions">Toptal.com</a></figcaption></figure><p><strong>Introduction:</strong></p><p>A window function performs a Data Analysis calculation across a set of table rows that are somehow related to the current row. Address the comparable type of calculation can be done with an aggregate function that gives a single row or grouped by condition (refer to Figure 1).</p><p>Window function does not cause rows to become grouped into a single output row. Rows retain their separate identities also able to access more than just the current row of the query result. (refer to Figure 1)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OjOX0bwNSxLkBIxzCL7Cpg.png" /><figcaption>Figure 1 — Difference between — Aggregated and Windows function</figcaption></figure><p><em>The database used to explain below concepts: Postgres database and Dataset: Available at </em><a href="https://github.com/GDhasade/Medium.com_Contents/tree/master/SQL"><em>Github Order_Table.csv</em></a></p><p><strong>Window Function Syntax:</strong></p><pre>Window_Function([All] expression) <br>OVER( [PARTITION BY expression_list] [ORDER BY order_list Row_or_ Range clause] )</pre><p>Each part of syntax has been explained as follows:</p><p><strong>Window_Function:</strong></p><p>There are 3 major types of window_functions</p><ol><li><strong>Window Aggregated Function:</strong> Consist one of the supporting aggregated function i.e. AVG(), COUNT(), MIN(), MAX(), SUM().</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oVKqRolUhV0e_HI1Ikga2Q.png" /><figcaption>Window Aggregated Function</figcaption></figure><p><strong>2. Window Ranking Aggregated Function: </strong>Consist one of the supporting ranking function i.e. RANK(), DENSE_RANK(), ROW_NUMBER().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WEvZRpjw1YJoApHE0vAsgw.png" /><figcaption><strong>Window Ranking Aggregated Function</strong></figcaption></figure><p><strong>3. Window Analytical Function: </strong>Consist one of the supporting ranking function i.e. FIRST_VALUE(), LAST_VALUE(), NTH_VALUE().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*68hAU2ntg_tKjs4o5SZlmg.png" /><figcaption><strong>Window Analytical Function</strong></figcaption></figure><p><strong>Over() clause:</strong></p><p>Over() clause is used to define the partitioning and ordering of rows (i.e. a window) for the functions (i.e. avg, count, etc.) to operate on. Hence, called windows function.</p><p>Over() clause have the following parameters:</p><ol><li><strong>Order by:</strong> Defines the logical order of the row.</li></ol><p><strong>For example:- </strong>Rank the product_ids with respect to the product price.</p><pre><strong>Query:</strong><br>Select product_id, price, Rank() OVER (ORDER BY price desc) AS Average_price<br>From orders;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*sXCEVQkN2HDnchyyCjhF6g.png" /><figcaption>Parameter — Order by</figcaption></figure><p><strong>2. Partition by:- </strong>Divides the query result set into <em>partitions </em>i.e. window function applied to each partition separately.</p><p><strong>For example:- </strong>Calculate the Average_Order_Price by gender i.e. partition by gender.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QC78yaRP0cCLl0b4QUtrTw.png" /><figcaption>Parameter — Partition by</figcaption></figure><p><strong>Observation:</strong></p><p>The average_price has been calculated by considering partition column i.e. gender. Hence, the same average_price has been calculated for each gender category.</p><p><strong>3. ROWS or RANGE clause:</strong> Limit the rows <em>within the partition</em> by specifying start and endpoints within the partition. The default value for Rows or Range clause is <em>RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW</em></p><p><strong>Types of Rows or Range clause:</strong></p><p><strong><em>a. UNBOUNDED PRECEDING AND CURRENT ROW:</em></strong></p><ul><li>It will start considering row values for aggregated function from ROW number 1 till current row.</li><li><strong>For example:-</strong></li></ul><pre><strong>Query:</strong></pre><pre>SELECT order_id, gender, price, <br>AVG(price) OVER (ORDER BY price ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Average_Price<br>FROM orders;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*8U192rrLvZl5WazgPl6FiA.png" /><figcaption><strong><em>UNBOUNDED PRECEDING AND CURRENT ROW</em></strong></figcaption></figure><ul><li><strong><em>Current Row no 7</em></strong>— Average_Price<strong><em>: </em></strong>( 163 + 163 +163 +163 +376 + 376 + 376) / 7 = 254.2857</li></ul><p><strong><em>b. UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING:</em></strong></p><ul><li>Unbounded Preceding consider the <em>first row </em>and Unbounded Following means it will consider the last row of computing column.</li><li><strong>For example:</strong></li></ul><pre><strong>Query:</strong><br>SELECT order_id, gender, price, <br>AVG(price) OVER (ORDER BY price ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS Average_Price<br>FROM orders;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*aeF_iga9SbYOPnWZwAcZvw.png" /><figcaption><strong><em>UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING</em></strong></figcaption></figure><ul><li>As we can see the average_price for each column is same, because it considers all values in the price column.</li></ul><p><strong>c. Other Types:</strong></p><p><strong><em>BETWEEN 1 PRECEDING AND 1 FOLLOWING</em>:</strong></p><pre><strong>Query:</strong><br>SELECT order_id, gender, price, <br>AVG(price) OVER (ORDER BY price ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS Average_Price<br>FROM orders;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*OkQUfvXN8wYgxie-baA6kA.png" /><figcaption><strong><em>BETWEEN 1 PRECEDING AND 1 FOLLOWING</em></strong></figcaption></figure><p>Average_Price calculation done by considering:</p><p>a. Current row value</p><p>b. One row preceding i.e. row above current_row value.</p><p>c. One row following i.e. row below the current_row value.</p><ul><li>Similarly, we can change the range of window as per requirement.</li></ul><p><strong>Conclusion:</strong></p><p>SQL Windows Functions are very powerful. In this blog, I tried to give a short overview of Windows Function.</p><p>I hope this blog helpful for you and hopefully it sparks your interest to see what windows function can do.</p><p>I highly encourage to read referenced documents for a more in-depth explanation.</p><p><strong>References/Study Materials:</strong></p><ol><li>postgresql.org (2019). <em>PostgreSQL: Documentation: 9.1: Window Functions</em>. [online] Postgresql.org. Available at: <a href="https://www.postgresql.org/docs/9.1/tutorial-window.html.">https://www.postgresql.org/docs/9.1/tutorial-window.html.</a></li><li>drill.apache.org (n.d.). <em>SQL Window Functions Introduction — Apache Drill</em>. [online] drill.apache.org. Available at: <a href="https://drill.apache.org/docs/sql-window-functions-introduction/">https://drill.apache.org/docs/sql-window-functions-introduction/</a> [Accessed 10 Nov. 2020].</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dc5cbdb1aa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/sql-windows-function-5dc5cbdb1aa">SQL Windows Function</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[Python Comprehensions With Implementation]]></title>
            <link>https://medium.com/data-science/python-comprehensions-with-implementation-852e17811bac?source=rss-8bc856b7f34c------2</link>
            <guid isPermaLink="false">https://medium.com/p/852e17811bac</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[comprehension]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Ganesh Dhasade]]></dc:creator>
            <pubDate>Wed, 21 Oct 2020 23:32:47 GMT</pubDate>
            <atom:updated>2020-10-22T02:21:10.259Z</atom:updated>
            <content:encoded><![CDATA[<h4>List | Dictionary | Set comprehensions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*3qrpRzEaUbd_pMqf" /><figcaption>Photo by: <a href="https://unsplash.com/@hudsoncrafted">Debby</a> | <a href="https://unsplash.com/">Unsplash.com</a></figcaption></figure><p><strong>Introduction:</strong></p><p>Python is a popular language that allows programmers to write elegant, easy-to-write and read code like plain English. The unique feature of Python is a different type of comprehensions.</p><p>In Python, there are three types of comprehensions viz. List, Dictionary and Set.</p><p>By the end of this blog, you’ll understand the full power of Python comprehensions and how to easily use its functionality.</p><ol><li><strong>LIST COMPREHENSION</strong></li></ol><p><strong>List: </strong>List is a collection of data surrounded by square brackets and each element are separated by a comma.</p><p><strong>List Comprehension: </strong>Is also surrounded by square brackets but instead of the list of elements inside it contain expression like for loop &amp;-or followed by if-clauses.</p><p><strong>Example:</strong></p><p>a. Create a List of the square of numbers between 1 to 100.</p><pre># Without List comprehension<br>SquaresWithoutComprehension = []<br>for i in range(1,101):<br>    SquaresWithoutComprehension.append(i**2)</pre><pre>## List Comprehension<br>SquaresWithComprehension = [i**2 for i in range(1,101)]<br></pre><p>b. List comprehension with the condition.</p><pre># Suppose we have List consist movie names with released year.</pre><pre>MoviesYear = [(&#39;Star Wars&#39;,2019),(&#39;Glass&#39;,2020),(&#39;The Upside&#39;,2018), (&#39;The LEGO Movie 2&#39;,2020),(&#39;Cold Pursuit&#39;,2017),<br>         (&#39;Hotel Mumbai&#39;,2020)]</pre><pre>## Problem: Create List of movies released in 2020?</pre><pre>Movies_20 = [title for (title, year) in MoviesYear if year == 2020]</pre><p>c. List comprehension — Mathematical Applications.</p><pre># Suppose we have List of numbers 1 to 10.</pre><pre>Numbers = [1,2,3,4,5,6,7,8,9,10]</pre><pre>## Problem 1: Perform scalar multiplication i.e multiply each number with 2 and store result into the List.</pre><pre>ScalarMultiplication  = [4*X for X in Numbers]</pre><pre>### Problem 2: Perform cartesian multiplication between List A and B.</pre><pre>A = [1,2,3,4]<br>B = [10,11,12,13]</pre><pre>CartesianProduct = [(a,b) for a in A for b in B]</pre><pre>##Output:</pre><pre>[(1, 10), (1, 11), (1, 12), (1, 13), (2, 10), (2, 11), (2, 12), (2, 13), (3, 10), (3, 11), (3, 12), (3, 13), (4, 10), (4, 11), (4, 12), (4, 13)]</pre><p><strong>Explanation:</strong></p><p>The above will produce the same result but when we use list comprehension the line of codes get reduced and the same operation is done with a single line of code.</p><p>2. <strong>DICTIONARY COMPREHENSION</strong></p><p><strong>Dictionary: </strong>A dictionary is a collection which is <strong>unordered, changeable and indexed</strong>. In Python dictionary written with curly brackets, and they have key and value pairs.</p><p>DictionaryExample = {“IDE”: “JupyterNotebook”, “Language”: “Python”, “Version”: 3}</p><p><strong>Dictionary Comprehension: </strong>A dictionary comprehension is also a collection which is unordered, changeable and indexed, where Key-Value pairs generated with help of expression.</p><p><strong>Example of Dictionary Comprehension:</strong></p><p>a. Create dictionary where Key as Alphabets and Value as the number of times alphabets occurred in the sentence (Dictionary definition).</p><pre># Sentence</pre><pre>DictDefination = &quot;A dictionary is a collection which is unordered, changeable and indexed. In Python written with curly brackets, and they have keys and values.&quot;</pre><pre>## Dictionary comprehension</pre><pre>AlphabetDictionary = {<br>        key: DictDefination.count(key) for key in DictDefination<br>                     }</pre><p>b. Dictionary Comprehension — Mathematical Application</p><pre># Problem: Create dictionary where Key as number and Value as cube of key i.e. number.</pre><pre>## Dictionary comprehension</pre><pre>NumSquareDictComprehension = {key:key**3 for key in range(1,10)}</pre><pre>OR</pre><pre>NumSquareDictComprehension = {f&quot;The square of {key} is&quot;:key**3 for key in range(1,10)}<br></pre><p>3. <strong>SET COMPREHENSION</strong></p><p><strong>Set: </strong>In Python Set is <strong>unique, unordered, mutable</strong> collection of elements. Set where elements enclosed with curly brackets and elements separated by a comma.</p><p>SetExample = {‘Python’,’Java’,’R’}</p><p><strong>Set Comprehension: </strong>Simillar to list comprehension but consist of a collection of <strong>unique, unordered, mutable </strong>elements, where dictionary elements inside it contain an expression.</p><p><strong>Example of Set Comprehension:</strong></p><p>a. Create Set consist squares of a number between 1 to 10.</p><pre>SquareSet = {num**2 for num in range (1,11)}</pre><p>b. Create Set of Unique elements available in the list.</p><pre># Suppose list having duplicate elements</pre><pre>CarBrands = [&#39;BMW&#39;,&#39;Chevrolet&#39;,&#39;Bentley&#39;,&#39;BMW&#39;]<br><br>## Set comprehension only give unique elements from the above List</pre><pre>CarBrandDict = {Brand for Brand in CarBrands}<br></pre><p><strong>Advantages of Comprehensions:</strong></p><ul><li>Easy to implement.</li><li>Reduce the number of lines of code.</li><li>Faster execution and utilise fewer resources.</li></ul><p><strong>Disadvantages of Comprehensions:</strong></p><ul><li>More number of comprehensions used in the program increase the complexity of code.</li><li>Complicate to understand expression working.</li></ul><p><strong>Conclusion:</strong></p><p>As discussed above, different types of comprehensions available in Python. Above implemented are basic examples expressions used in comprehensions can be used to call the functions. Most often, list and dictionary comprehension use to simplify the code.</p><p>Hope, this blog helps you understand some effective and easy-to-use Python techniques.</p><p>Thank you for reading!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=852e17811bac" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/python-comprehensions-with-implementation-852e17811bac">Python Comprehensions With Implementation</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Series Forecasting]]></title>
            <link>https://g-dhasade16.medium.com/time-series-forecasting-358df61a6a09?source=rss-8bc856b7f34c------2</link>
            <guid isPermaLink="false">https://medium.com/p/358df61a6a09</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Ganesh Dhasade]]></dc:creator>
            <pubDate>Thu, 24 Sep 2020 21:21:23 GMT</pubDate>
            <atom:updated>2020-09-24T21:34:42.749Z</atom:updated>
            <content:encoded><![CDATA[<p>Part 1: Basic Introduction About Time-Series Forecasting</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*wYNxzIhQCwPvnHa9" /><figcaption>Photo by:<a href="https://unsplash.com/@ikukevk"> Kevin Ku</a> |<a href="https://unsplash.com/"> Unsplash.com</a></figcaption></figure><p><strong>Introduction:</strong></p><p>Time Series Forecasting is the use of the statistical model to predict future value based on past observation/results. Use any variables tracked and collected over time. For example, annual population, daily stock prices, daily-weekly-quarterly sales, etc.</p><p><strong>Time Series Data Characteristics &amp; Objectives:</strong></p><ul><li>The data completely depend on data and time. Hence, if the<strong> order</strong> of date or time change leads to a change in the meaning of data.</li><li>Data collection must be done sequentially and at an equal interval of time.</li><li>Once data collection is done properly, the next step is to <strong>identify patterns</strong> with help of a sequence of observations and <strong>forecast/predict</strong> the future values in Time series.</li></ul><p><strong>Time Series Components</strong></p><p><strong>1. Time Series Plot</strong></p><p>In Time-Series plot always, X-axis indicates Date/Time and Y-axis indicates Target Variable. For example, Want to predict monthly sales of the shop. Then X-axis: Days and Y-axis: Per day sales value.</p><p><strong>2. Types of Trend in Time-Series plot</strong></p><p>There are 3 types of trend can be observed in Time-Series graph. Also, each observed trend in Time-Series called Trend Cycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/0*fBBvWxQO1d_FNQwK.png" /><figcaption>Type of Trend | Image by: <a href="https://swissborg.com/blog/how-to-apply-technical-analysis-to-cryptocurrencies">swissborg.com</a></figcaption></figure><ul><li><strong>Uptrend:</strong> The trend having HH (Higher High) &amp; HL (Higher Low).</li><li><strong>Downtrend: </strong>The trend having LH(Lower High) &amp; LL (Lower Low).</li><li><strong>Horizontal or Sideway Trend:</strong> The trend moving with same or no variation in time series and moving horizontally.</li></ul><p><strong>3. Seasonality</strong></p><ul><li>Time-Series exhibits a repeated pattern at a fixed interval of time. For example, Sales of Air-Conditioner increase during summers and decrease during winters.</li><li>Seasonality trend helps business to manage their inventories, staffs and other business-related decision.</li></ul><p><strong>3. Cyclical Pattern</strong></p><ul><li>Time-Series has no fixed period for rising/fall pattern.</li><li>Also, there is no repeated pattern within each year i.e no seasonality observed.</li><li>The magnitude of trend cycles changes more frequently, hence much harder to predict the future trend.</li></ul><p><strong>Types of Time-Series Predictive/Forecasting Models</strong></p><ol><li><strong>ETS — Error Trend Seasonality Model</strong></li></ol><p>ETS models are <strong>non-stationary.</strong> ETS models are considered as exponential smoothing and then state-space. ETS model describes how unobserved components of the data (error, trend, and seasonality) change over time.</p><p>In the ETS model giving more weight to most recent observations or values with weights gradually gets smaller as observations get older.</p><p>There are 4 types of ETS methods:</p><ul><li>Simple Exponential Smoothing Method (SES)</li><li>Holt’s Linear Trend Method (HLT)</li><li>Exponential Trend Method (ET)</li><li>Holt’s-Winter Seasonal Method (HWS)</li></ul><p><strong>2. ARIMA — Auto-Regressive Integrated Moving Average Model</strong></p><p>ARIMA models are <strong>stationary</strong>. ARIMA models focus on autocorrelation in data and forecast future trends.</p><p>There are two types of ARIMA models i.e. non-seasonal and seasonal.</p><p><strong>Non-Seasonal ARIMA:</strong></p><p>ARIMA(p,d,m)</p><p>Where: p = Auto regressive value,</p><p>d = Number of transformation done to make data stationery,</p><p>m = Moving Average</p><p><strong>Seasonal ARIMA:</strong></p><p>ARIMA (p,d,m) (P,D,M) m</p><p>Where:</p><p>p: Autoregressive value,</p><p>d: Number of transformation done to make data stationery,</p><p>m: Moving Average</p><p>P, D, M: Autoregressive, number of transformation done to make data stationery, Moving Average of Seasonal Data.</p><p>m: Number of periods in each season</p><p><strong>Conclusion:</strong></p><p>In this blog, I try to summarise the Time-Series its characteristics, types and about forecasting model. In upcoming blogs, I will explain each Time-Series Forecasting models (ETS &amp; ARIMA) in details with Implementation using python.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=358df61a6a09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ways To Handle Categorical Data Before Train ML Models With Implementation.]]></title>
            <link>https://medium.com/data-science/ways-to-handle-categorical-data-before-train-ml-models-with-implementation-ffc213dc84ec?source=rss-8bc856b7f34c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffc213dc84ec</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-preparation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[categorical-data]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Ganesh Dhasade]]></dc:creator>
            <pubDate>Thu, 10 Sep 2020 00:36:40 GMT</pubDate>
            <atom:updated>2020-09-11T14:29:40.566Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ways To Handle Categorical Data With Implementation</h3><h4>Implemented popular techniques using Python</h4><p>In my last blogs, I explained <a href="https://medium.com/@g.dhasade16/missing-data-its-types-9f59e897843f">types of missing values</a> and different ways to handle <a href="https://medium.com/swlh/ways-to-handle-continous-column-missing-data-its-implementations-4704f52ac9c3">Continous</a> and <a href="https://medium.com/analytics-vidhya/ways-to-handle-categorical-column-missing-data-its-implementations-15dc4a56893">Categorical</a> missing values with implementation.</p><p>After handle missing values in the dataset, the next step was to handle categorical data. In this blog, I will explain different ways to handle categorical features/columns along with implementation using python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZDIhEEkcV01tS2IhGgQoFw.png" /><figcaption>Photo by: <a href="https://unsplash.com/@altumcode">AltumCode</a> | <a href="https://unsplash.com/">Unsplash.com</a></figcaption></figure><p><strong>Introduction: </strong>All Machine Learning models are some kind of mathematical model that needs numbers to work with. Categorical data have possible values (categories) and it can be in text form. For example, Gender: Male/Female/Others, Ranks: 1st/2nd/3rd, etc.</p><p>While working on a data science project after handling the missing value of datasets. The next work is to handle categorical data in datasets before applying any ML models.</p><p>First, let’s understand the types of categorical data:</p><ol><li><strong>Nominal Data:</strong> The nominal data called<strong><em> labelled/named</em></strong> data. Allowed to change the order of categories, change in order doesn’t affect its value. For example, Gender (Male/Female/Other), Age Groups (Young/Adult/Old), etc.</li><li><strong>Ordinal Data:</strong> Represent <strong><em>discretely and ordered units</em></strong>. Same as nominal data but have ordered/rank. Not allowed to change the order of categories. For example, Ranks: 1st/2nd/3rd, Education: (High School/Undergrads/Postgrads/Doctorate), etc.</li></ol><p>Ways to handle categorical features:</p><p>The dataset used to explain is Titanic (<a href="https://www.kaggle.com/c/titanic">Kaggle dataset</a>):</p><pre>import pandas as pd<br>import numpy as np<br>Data = pd.read_csv(&quot;train.csv&quot;)<br>Data.isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/0*sj-1sl1oG1DRu0vE.png" /><figcaption>DataType — Object is categorical features in the dataset.</figcaption></figure><ol><li><strong>Create Dummies</strong></li></ol><p><strong><em>Description: </em></strong>Create dummies or binary type columns for each category in the object/ category type feature. The value for each row is 1 if that category is available in that row else 0. To create dummies use pandas get_dummies() function.</p><p><strong><em>Implementation:</em></strong></p><pre>DataDummies = pd.get_dummies(Data)<br>DataDummies</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v4chWzELkmSlXeQ-zpFSlw.png" /><figcaption>Example: Passenger class create 3 new columns.</figcaption></figure><p><strong><em>Advantage:</em></strong></p><ul><li>Easy to use and fast way to handle categorical column values.</li></ul><p><strong><em>Disadvantage:</em></strong></p><ul><li>get_dummies method is not useful when data have many categorical columns.</li><li>If the category column has many categories leads to add many features into the dataset.</li></ul><p>Hence, This method is only useful when data having less categorical columns with fewer categories.</p><p><strong>2. Ordinal Number Encoding</strong></p><p><strong><em>Description: </em></strong>When the categorical variables are ordinal, the easiest approach is to replace each label/category by some ordinal number based on the ranks. In our data Pclass is ordinal feature having values First, Second, Third so each category replaced by its rank i.e 1,2,3 respectively.</p><p><strong><em>Implementation:</em></strong></p><p>Step 1: Create a dictionary with key as category and values with its rank.</p><p>Step 2: Create a new column and map the ordinal column with the created dictionary.</p><p>Step 3: Drop the original column.</p><pre># 1. <br>PClassDict =   {   &#39;First&#39;:1,<br>                    &#39;Second&#39;:2,<br>                     &#39;Third&#39;:3,              <br>                }</pre><pre># 2. <br>Data[&#39;Ordinal_Pclass&#39;] = Data.Pclass.map(PClassDict)</pre><pre># Display result<br>      <br>      Data[[&#39;PassengerId&#39;, &#39;Pclass&#39;, &#39;Ordinal_Pclass&#39;]].head(10)</pre><pre># 3.</pre><pre>Data = Data.drop(&#39;Pclass&#39;, axis = 1)</pre><p><strong><em>Advantage:</em></strong></p><ul><li>The easiest way to handle the ordinal feature in the dataset.</li></ul><p><strong><em>Disadvantage:</em></strong></p><ul><li>Not good for Nominal type features in the dataset.</li></ul><p><strong>3. Count / Frequency Encoding</strong></p><p><strong><em>Description: </em></strong>Replace each category with its frequency/number of time that category occurred in that column.</p><p><strong><em>Implementation:</em></strong></p><p>Step 1. Create Dictionaries with key as category name and value with a count of categories i.e frequency of that category in each categorical column.</p><p>Step 2. Create a new column which acts as a weight for that category and map with its respective dictionary.</p><p>Step 3. Drop Orginal Columns.</p><pre># 1.</pre><pre>Pclass_Dict = Data[&#39;Pclass&#39;].value_counts()<br>Salutation_Dict = Data[&#39;Salutation&#39;].value_counts()<br>Sex_Dict = Data[&#39;Sex&#39;].value_counts()<br>Embarked_Dict = Data[&#39;Embarked&#39;].value_counts()<br>Cabin_Serial_Dict = Data[&#39;Cabin_Serial&#39;].value_counts()<br>Cabin_Dict = Data[&#39;Cabin&#39;].value_counts()</pre><pre># 2.</pre><pre>Data[&#39;Encoded_Pclass&#39;] = Data[&#39;Pclass&#39;].map(Pclass_Dict)<br>Data[&#39;Salutation_Dict&#39;] = Data[&#39;Salutation&#39;].map(Salutation_Dict)<br>Data[&#39;Sex_Dict&#39;] = Data[&#39;Sex&#39;].map(Sex_Dict)<br>Data[&#39;Embarked_Dict&#39;] = Data[&#39;Embarked&#39;].map(Embarked_Dict)<br>Data[&#39;Cabin_Serial_Dict&#39;] = Data[&#39;Cabin_Serial&#39;].map(Cabin_Serial_Dict)<br>Data[&#39;Cabin_Dict&#39;] = Data[&#39;Cabin&#39;].map(Cabin_Dict)</pre><pre># Display Result</pre><pre>Data[[&#39;Pclass&#39;,&#39;Encoded_Pclass&#39;,&#39;Salutation&#39;,&#39;Salutation_Dict&#39;,&#39;Sex&#39;       ,&#39;Sex_Dict&#39;,&#39;Embarked&#39;,&#39;Embarked_Dict&#39;,&#39;Cabin_Serial&#39;,&#39;Cabin_Serial_Dict&#39;,&#39;Cabin&#39;,&#39;Cabin_Dict&#39;]].head(10)</pre><pre># 3. <br>Data = Data.drop([&#39;Pclass&#39;,&#39;Salutation&#39;,&#39;Sex&#39;,&#39;Embarked&#39;,&#39;Cabin_Serial&#39;,&#39;Cabin&#39;], axis = 1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kCxNQWM76aSIDSlA2xN0Ug.png" /><figcaption>Each category and its frequency count.</figcaption></figure><p><strong><em>Advantage:</em></strong></p><ul><li>East to implement.</li><li>Not increasing any extra features.</li></ul><p><strong><em>Disadvantage:</em></strong></p><ul><li>Not able to handle the same number of categories i.e provide the same values to both categories.</li></ul><p><strong>4. Target/Guided Encoding</strong></p><p><strong><em>Description: </em></strong>Here, the category of the column has been replaced with its depending join probability ranking with respect to Target column.</p><p><strong><em>Implementation: </em></strong>To show the implementation I am using Cabin column with respect to Survived target column. The same steps are applicable for any ordinal column in the dataset.</p><p>Step 1. Replace original cabin value with the first character of the cabin name.</p><p>Step 2. Calculate the joint probability of each category based on the target column value.</p><p>Step 3. Create a list with sorted index in ascending order of join probabilities.</p><p>Step 4. Create a dictionary where key as category name in cabin and values as joint probability ranking.</p><p>Step 5. Create a new column and map cabin values with dictionary joint probability ranking.</p><p>Step 6. Delete original cabin column.</p><pre><em># 1.</em></pre><pre>Data[&#39;Cabin&#39;] = Data[&#39;Cabin&#39;].astype(str).str[0]</pre><pre><em># 2.</em></pre><pre>Data.groupby([&#39;Cabin&#39;])[&#39;Survived&#39;].mean()</pre><pre><em># 3.</em></pre><pre>Encoded_Lables = Data.groupby([&#39;Cabin&#39;])  [&#39;Survived&#39;].mean().sort_values().index</pre><pre><em># 4.</em></pre><pre>Encoded_Lables_Ranks = { k:i for i, k in enumerate(Encoded_Lables, 0) }</pre><pre># 5.</pre><pre>Data[&#39;Cabin_Encoded&#39;] = Data[&#39;Cabin&#39;].map(Encoded_Lables_Ranks)</pre><pre># 6.</pre><pre>Data = Data.drop(&#39;Cabin&#39;, axis = 1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*R0nNO4S08OkvlpDo0Hwdtw.png" /><figcaption>Cabin Values with Join Probability ranking with respect to target column.</figcaption></figure><p><strong><em>Advantages:</em></strong></p><ul><li>It doesn’t affect the volume of the data i.e not add any extra features.</li><li>Helps the machine learning model to learn faster.</li></ul><p><strong><em>Disadvantages:</em></strong></p><ul><li>Typically, mean or joint probability encoding leads for over-fitting.</li><li>Hence, to avoid overfitting cross-validation or some other approach is required most of the time.</li></ul><p><strong>5. Mean Encoding</strong></p><p><strong><em>Description: </em></strong>Simillar to target/guided encoding only difference is here we replace category with the mean value with respect to target column. Here also we implement with cabin and survived target column.</p><p><strong><em>Implementation:</em></strong></p><p>Step 1. Calculate the mean for each category in the cabin column with respect to the target column (Survived).</p><p>Step 2. Create a new column and replace by mean i.e map cabin column categories with its encoded mean dictionary.</p><p>Step 3. Drop original cabin column</p><pre># 1.</pre><pre>Encoded_Mean_Dict = Data.groupby([&#39;Cabin&#39;])[&#39;Survived&#39;].mean().to_dict()</pre><pre># 2.</pre><pre>Data[&#39;Cabin_Mean_Encoded&#39;] = Data[&#39;Cabin&#39;].map(Encoded_Mean_Dict)</pre><pre># Display result</pre><pre>Data[[&#39;Cabin&#39;,&#39;Cabin_Mean_Encoded&#39;]].head()</pre><pre># 3.</pre><pre>Data = Data.drop(&#39;Cabin&#39;, axis = 1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*o54J4u5nyl845AIo761M_Q.png" /><figcaption>Cabin categories with its corresponding mean with respect to target column.</figcaption></figure><p><strong><em>Advantages:</em></strong></p><ul><li>Capture information within labels or categories, rendering more predictive features.</li><li>Create a monotonous relationship between the independent variable and the target variable.</li></ul><p><strong><em>Disadvantages:</em></strong></p><ul><li>May leads to overfit the model, to overcome this problem cross-validation is use most of the time.</li></ul><p><strong>6. Probability Ratio Encoding</strong></p><p><strong><em>Description: </em></strong>Here category of the column is replaced with a probability ratio with respect to Target variable. Here I am using Cabin as an independent variable and its categories is replaced with a probability ratio of person Survived vs Died in each cabin.</p><p><strong><em>Implementation:</em></strong></p><p>Step 1. Replace original cabin value with the first character of the cabin name.</p><p>Step 2. Find percentage (%) of people survived in a particular cabin and store into new dataframe.</p><p>Step 3. Create a new column into probability survived dataframe with the probability of people getting dead in a particular cabin.</p><p>Step 4. Create one more new column into probability survived dataframe i.e ratio of survived and died probability.</p><p>Step 5. Create a dictionary with probability ratio column.</p><p>Step 6. Create a new column in Data and replace by mapping cabin column categories with its encoded probability ratio dictionary.</p><p>Step 7. Drop original cabin column.</p><pre>#1. </pre><pre>Data[&#39;Cabin&#39;]  = Data[&#39;Cabin&#39;].astype(str).str[0]</pre><pre># 2. </pre><pre>Probability_Survived = Data.groupby([&#39;Cabin&#39;])[&#39;Survived&#39;].mean()<br>Probability_Survived = pd.DataFrame(Probability_Survived)</pre><pre># 3.</pre><pre>Probability_Survived[&#39;Died&#39;] = 1 - Probability_Survived[&#39;Survived&#39;]</pre><pre># 4.</pre><pre>Probability_Survived[&#39;Prob_Ratio&#39;] = Probability_Survived[&#39;Survived&#39;] / Probability_Survived[&#39;Died&#39;]</pre><pre># 5.</pre><pre>Encode_Prob_Ratio = Probability_Survived[&#39;Prob_Ratio&#39;].to_dict()</pre><pre># 6.</pre><pre>Data[&#39;Encode_Prob_Ratio&#39;] = Data[&#39;Cabin&#39;].map(Encode_Prob_Ratio)</pre><pre># Display result</pre><pre>Data[[&#39;Cabin&#39;,&#39;Encode_Prob_Ratio&#39;]].head(10)</pre><pre># 7.</pre><pre>Data = Data.drop(&#39;Cabin&#39;, axis = 1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*0lp8ZBIu7u9zVSNBLeGGwg.png" /><figcaption>Cabin categories and its corresponding probability ratio of survival.</figcaption></figure><p><strong><em>Advantages:</em></strong></p><ul><li>Not increase any extra feature.</li><li>Captures information within the labels or category hence creates more predictive features.</li><li>Creates a monotonic relationship between the variables and the target. So it’s suitable for linear models.</li></ul><p><strong><em>Disadvantages:</em></strong></p><ul><li>Not defined when the denominator is 0.</li><li>Same as the above two methods lead to overfitting to avoid and validate usually cross-validation has been performed.</li></ul><p><strong>Conclusion:</strong></p><p>Hence, in this blogs, I try to explain about most widely used ways to handle categorical variables while preparing data for machine learning. The actual code notebook available at <a href="https://github.com/GDhasade/Medium.com_Contents/blob/master/Handle_Categorical_Data.ipynb">https://github.com/GDhasade/Medium.com_Contents/blob/master/Handle_Categorical_Data.ipynb</a></p><p>For more information please visit <a href="http://contrib.scikit-learn.org/category_encoders/index.html">http://contrib.scikit-learn.org/category_encoders/index.html</a>.</p><p>References:</p><ol><li>Scikit-learn.org. (2019). <em>sklearn.preprocessing.OneHotEncoder — scikit-learn 0.22 documentation</em>. [online] Available at: <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html.">https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html.</a></li><li>‌contrib.scikit-learn.org. (n.d.). <em>Category Encoders — Category Encoders 2.2.2 documentation</em>. [online] Available at: <a href="http://contrib.scikit-learn.org/category_encoders/index.html.">http://contrib.scikit-learn.org/category_encoders/index.html.</a></li><li>Krish Naik (2019). <em>Feature Engineering-How to Perform One Hot Encoding for Multi Categorical Variables</em>. <em>YouTube</em>. Available at: <a href="https://www.youtube.com/watch?v=6WDFfaYtN6s&amp;list=PLZoTAELRMXVPwYGE2PXD3x0bfKnR0cJjN&amp;ab_channel=KrishNaik">https://www.youtube.com/watch?v=6WDFfaYtN6s&amp;list=PLZoTAELRMXVPwYGE2PXD3x0bfKnR0cJjN&amp;ab_channel=KrishNaik</a> [Accessed 10 Sep. 2020].</li></ol><p>‌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffc213dc84ec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/ways-to-handle-categorical-data-before-train-ml-models-with-implementation-ffc213dc84ec">Ways To Handle Categorical Data Before Train ML Models With Implementation.</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ways To Handle Categorical Column Missing Data & Its Implementations]]></title>
            <link>https://medium.com/analytics-vidhya/ways-to-handle-categorical-column-missing-data-its-implementations-15dc4a56893?source=rss-8bc856b7f34c------2</link>
            <guid isPermaLink="false">https://medium.com/p/15dc4a56893</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[handling-missing-values]]></category>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Ganesh Dhasade]]></dc:creator>
            <pubDate>Tue, 01 Sep 2020 18:29:23 GMT</pubDate>
            <atom:updated>2020-09-04T13:15:04.639Z</atom:updated>
            <content:encoded><![CDATA[<p>In my last blog <a href="https://medium.com/@g.dhasade16/ways-to-handle-continous-column-missing-data-its-implementations-4704f52ac9c3">Link</a>, I explained different ways to handle Continuous column missing data and its implementation.</p><p>In this blog, I will explain how to handle missing values of the Categorical data column in the dataset with implementation using python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EK_W4UpwF5rDKyJF.png" /><figcaption>Image from: 365datascience.com</figcaption></figure><p><strong>Discrete/ Categorical Data: </strong>discrete data is quantitative data that can be counted and has a finite number of possible values or data which may be divided into groups e.g. days in a week, number of months in a year, sex (Male/Female/Others), Grades (High/Medium/Low), etc.</p><p>The dataset used to explain is Titanic (<a href="https://www.kaggle.com/c/titanic">Kaggle dataset</a>):</p><pre>import pandas as pd<br>import numpy as np<br>Data = pd.read_csv(&quot;train.csv&quot;)<br>Data.isnull().sum()<br>Data.dtypes()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*LpabdvRdtfLBS5LwnnFpSw.png" /><figcaption>Cabin_Serial, Cabin and Embarked Categorical Variable has NAN values</figcaption></figure><p>The number of categories in each column:</p><pre># Code to get number of categories in missing value columns</pre><pre>print(&quot;Number of Categories in: &quot;)</pre><pre>for ColName in DataFrame[[&#39;Embarked&#39;,&#39;Cabin_Serial&#39;,&#39;Cabin&#39;]]:<br>    print(&quot;{} = {}&quot;.format(ColName,       len(DataFrame[ColName].unique())))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*M1vzT0KRmXd6leNZEKLuYA.png" /></figure><ol><li><strong>Frequent Categorical Imputation</strong></li></ol><p><strong><em>Assumptions</em></strong>: Data is Missing At Random (MAR) and missing values look like the majority.</p><p><strong><em>Description: </em></strong>Replacing NAN values with the most frequent occurred category in variable/column.</p><p><strong><em>Implementation:</em></strong></p><p>Step 1: Find which category occurred most in each category using mode().</p><p>Step 2: Replace all NAN values in that column with that category.</p><p>Step 3: Drop original columns and keep newly imputed columns.</p><pre>#1. Function to replace NAN values with mode value</pre><pre>def impute_nan_most_frequent_category(DataFrame,ColName):<br>    # .mode()[0] - gives first category name<br>     most_frequent_category=DataFrame[ColName].mode()[0]<br>    <br>    # replace nan values with most occured category<br>     DataFrame[ColName + &quot;_Imputed&quot;] = DataFrame[ColName]<br>     DataFrame[ColName + &quot;_Imputed&quot;].fillna(most_frequent_category,inplace=True)</pre><pre>#2. Call function to impute most occured category</pre><pre>for Columns in [&#39;Embarked&#39;,&#39;Cabin_Serial&#39;,&#39;Cabin&#39;]:<br>    impute_nan_most_frequent_category(DataFrame,Columns)<br>    <br># Display imputed result<br>DataFrame[[&#39;Embarked&#39;,&#39;Embarked_Imputed&#39;,&#39;Cabin_Serial&#39;,&#39;Cabin_Serial_Imputed&#39;,&#39;Cabin&#39;,&#39;Cabin_Imputed&#39;]].head(10)</pre><pre>#3. Drop actual columns</pre><pre>DataFrame = DataFrame.drop([&#39;Embarked&#39;,&#39;Cabin_Serial&#39;,&#39;Cabin&#39;], axis = 1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Te-d7LIUJ0HFpQIIWctbhA.png" /><figcaption>Impute most occurred category in place of NAN value</figcaption></figure><p><strong><em>Advantage:</em> </strong>Simple and easy to implement for categorical variables/columns.</p><p><strong><em>Disadvantage:</em></strong></p><ul><li>Features having a max number of null values may bias prediction if replace with the most occurred category.</li><li>It distorts the relation of the most frequent label.</li></ul><p><strong>2. Adding a Variable To Capture NAN</strong></p><p><strong><em>Assumptions</em></strong>: No assumption, can be work with all type categorical columns.</p><p><strong><em>Description: </em></strong>Replace NAN categories with most occurred values, and add a new feature to introduce some weight/importance to non-imputed and imputed observations.</p><p><strong><em>Implementation:</em></strong></p><p>Step 1. Create a new column and replace 1 if the category is NAN else 0. This column is an importance column to the imputed category.</p><p>Step 2. Replace NAN value with most occurred category in the actual column.</p><pre># Function to impute most occured category and add importance vairable</pre><pre>def impute_nan_add_vairable(DataFrame,ColName):<br>    #1. add new column and replace if category is null then 1 else 0</pre><pre>    DataFrame[ColName+&quot;_Imputed&quot;] =   np.where(DataFrame[ColName].isnull(),1,0)<br>    <br>    # 2. Take most occured category in that vairable (.mode())<br>    <br>    Mode_Category = DataFrame[ColName].mode()[0]<br>    <br>    ## 2.1 Replace NAN values with most occured category in actual vairable<br>    <br>    DataFrame[ColName].fillna(Mode_Category,inplace=True)</pre><pre># Call function to impute NAN values and add new importance feature</pre><pre>for Columns in [&#39;Embarked&#39;,&#39;Cabin_Serial&#39;,&#39;Cabin&#39;]:<br>    impute_nan_add_vairable(DataFrame,Columns)<br>    <br># Display top 10 row to see the result of imputation</pre><pre>DataFrame[[&#39;Embarked&#39;,&#39;Embarked_Imputed&#39;,&#39;Cabin_Serial&#39;,&#39;Cabin_Serial_Imputed&#39;,&#39;Cabin&#39;,&#39;Cabin_Imputed&#39;]].head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OmhsalT0Kbij3TN2LIoFYw.png" /><figcaption>Imputed NAN with the most occurred category and add a new Importance variable/column.</figcaption></figure><p><strong><em>Advantage:</em> </strong>Capture the importance of missingness.</p><p><strong><em>Disadvantage:</em></strong></p><ul><li>Creating Additional Features(Curse of Dimensionality) e.g. if there are 10 columns have null values need to create 10 extra columns.</li><li>Potentially misunderstood data &amp; the number of missing data should be large enough.</li></ul><p><strong>3. Create a New Category (Random Category) for NAN Values</strong></p><p><strong><em>Assumptions</em></strong>: No assumption</p><p><strong><em>Description: </em></strong>Create a new category for NAN values i.e random category.</p><p><strong><em>Implementation:</em></strong></p><p>Step 1. Replace NAN value with a new name (here we create a new category as <em>Unknown</em>).</p><p>Step 2. Display result</p><pre>#1. Function to impute null value with new category<br>def impute_nan_create_category(DataFrame,ColName):<br>     DataFrame[ColName] = np.where(DataFrame[ColName].isnull(),&quot;Unknown&quot;,DataFrame[ColName])</pre><pre>## Call function to create new category for variables<br>for Columns in [&#39;Embarked&#39;,&#39;Cabin_Serial&#39;,&#39;Cabin&#39;]:<br>    impute_nan_create_category(DataFrame,Columns)</pre><pre>#2. Display result<br>DataFrame[[&#39;Embarked&#39;,&#39;Cabin_Serial&#39;,&#39;Cabin&#39;]].head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*cRt99dQeHMA7YKJMDkhJNw.png" /><figcaption>Add new category</figcaption></figure><p><strong><em>Advantage:</em> </strong>Simple and easy to implement for categorical variables/columns and preserves the variance.</p><p><strong><em>Disadvantage:</em></strong></p><ul><li>May create random data if the missing category is more.</li><li>Doesn’t give good results when missing data is a high percentage of the data.</li></ul><p><strong>Conclusion:</strong></p><p>The above implementation is to explain different ways we can handle missing categorical data. The most widely used methods are Create a New Category (Random Category) for NAN Values and Most frequent category imputation.</p><p><strong><em>For reference: </em></strong>Jupyter notebook — code available at GitHub: <a href="https://github.com/GDhasade/Medium.com_Contents/blob/master/Handle_Categorical_Missing_Data.ipynb">https://github.com/GDhasade/Medium.com_Contents/blob/master/Handle_Categorical_Missing_Data.ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15dc4a56893" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/ways-to-handle-categorical-column-missing-data-its-implementations-15dc4a56893">Ways To Handle Categorical Column Missing Data &amp; Its Implementations</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[Ways to Handle Continous Column Missing Data & Its Implementations]]></title>
            <link>https://medium.com/swlh/ways-to-handle-continous-column-missing-data-its-implementations-4704f52ac9c3?source=rss-8bc856b7f34c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4704f52ac9c3</guid>
            <category><![CDATA[data-preparation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-preprocessing]]></category>
            <category><![CDATA[handling-missing-values]]></category>
            <dc:creator><![CDATA[Ganesh Dhasade]]></dc:creator>
            <pubDate>Tue, 01 Sep 2020 12:38:40 GMT</pubDate>
            <atom:updated>2020-09-07T10:38:26.508Z</atom:updated>
            <content:encoded><![CDATA[<p>In my last blog <a href="https://medium.com/@g.dhasade16/missing-data-its-types-9f59e897843f">Link</a>, I explained missing values and their types.</p><p>In this blog, I will explain how to handle missing values for the Continuous data column in the dataset with implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*6_hjb3cvmpcpmGm2" /><figcaption>Photo by: Scott Graham | Unsplash.com</figcaption></figure><p><strong>Continous Data:</strong> Continuous data is quantitative data that can be measured, it has an infinite number of possible values within a selected range e.g. temperature range, height, weight, etc.</p><p>The dataset used to explain is Titanic (<a href="https://www.kaggle.com/c/titanic">Kaggle dataset</a>)</p><pre>import pandas as pd<br>import numpy as np<br>Data = pd.read_csv(&quot;train.csv&quot;)<br>Data.isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*ijhwgwNsXCe2rL9j97wKqA.png" /><figcaption>Null values present in the dataset</figcaption></figure><ol><li><strong>Mean / Median / Mode Imputation:</strong></li></ol><p><strong><em>Assumption:</em></strong> Data is Missing Completely at Random(MCAR).</p><p><strong><em>Description: </em></strong>Replacing NAN values with the most frequent occurrence of variable.</p><p><strong><em>Implementation: </em></strong>Handle Age missing values</p><pre># function use to impute_nan values with mean/median/mode<br>def impute_nan(DataFrame, ColumnName, ImputeValue):<br>    DataFrame[ColumnName + &quot;_Imputed&quot;] =                                                     DataFrame[ColumnName].fillna(ImputeValue)</pre><pre># Call function to impute median value<br>median = Data.Age.median()<br>impute_nan(Data, &#39;Age&#39;, median)</pre><p>Similarly, we can replace the NAN value with mean/mode.</p><p>This method has disadvantage i.e. impact the correlation and change distortion in original variance. To understand the impact, the below code used to plot data to see the distribution of variance.</p><pre># Code to plot distribution of vairance in data columns</pre><pre>fig = plt.figure()<br>ax = fig.add_subplot(111)<br>Data[&#39;Age&#39;].plot(kind=&#39;kde&#39;, ax=ax)<br>Data[&#39;Age_Imputed&#39;].plot(kind=&#39;kde&#39;, ax=ax, color=&#39;red&#39;)<br>lines, labels = ax.get_legend_handles_labels()<br>ax.legend(lines, labels, loc=&#39;best&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*A7hj3yiOK_Z75fXxeS5kQQ.png" /><figcaption>Imputation of mean/median/mode adds variance into data.</figcaption></figure><p><strong>2. Random Sample Imputation</strong></p><p><strong><em>Assumption:</em></strong> Data is Missing Completely at Random(MCAR).</p><p><strong><em>Description: </em></strong>Taking random observation from the dataset and use these observations to replace the NAN values.</p><p><strong><em>Implementation: </em></strong>Handle Age missing values</p><p>Step 1: Create a copy of the Age column.</p><p>Step 2: Select random sample values to fill the NAN (Ignore NAN values and select only non-NAN values.)</p><p>Step 3: Replace NAN values with random sample values with the index of NAN values.</p><pre># function to impute_nan values with random observations<br>def impute_random_nan(Data,ColName):<br>    <br>    #Make copy of Column<br>    Data[ColName+&quot;_random&quot;]=Data[ColName]<br>    <br>    #Select random sample value to fill the na<br>    # .dropna() - to ignore NAN values and select non-NAN values<br>    <br>    random_sample =       Data[ColName].dropna().sample(Data[ColName].isnull().sum(),random_state=0)<br>    <br>    # Merge - pandas need to have same index in order to merge the dataset.<br>    <br>   random_sample.index = Data[Data[ColName].isnull()].index<br>    <br>    Data.loc[Data[ColName].isnull(),ColName+&#39;_random&#39;]=random_sample</pre><pre>#Call function to impute median value<br>median = Data.Age.median()<br>impute_nan(Data, &#39;Age&#39;, median)</pre><p><strong><em>Advantage:</em></strong> Not add or minimize the distortion in imputed values. Let&#39;s plot the curves to see the variance distribution.</p><pre># Code to plot distribution of vairance in data columns<br>fig = plt.figure()<br>ax = fig.add_subplot(111)<br>DataFrame[&#39;Age&#39;].plot(kind=&#39;kde&#39;, ax=ax)<br>DataFrame[&#39;Age_random&#39;].plot(kind=&#39;kde&#39;, ax=ax, color=&#39;red&#39;)<br>lines, labels = ax.get_legend_handles_labels()<br>ax.legend(lines, labels, loc=&#39;best&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*j2xi2NDOq44RLKfPt1gdZQ.png" /><figcaption>Distribution of variance is minimum after imputation.</figcaption></figure><p><strong><em>Disadvantage: </em></strong>This randomness does not work in every situation.</p><p><strong>3. Capturing NAN Values With a New Feature</strong></p><p><strong><em>Assumption:</em></strong> Data is NOT Missing Completely at Random(MCAR).</p><p><strong><em>Description: </em></strong>Add a new feature to introduce some weight/importance to non-imputed and imputed observations.</p><p><strong><em>Implementation: </em></strong>Handle Age missing values</p><p>Step 1: Replace null values with mean/mode/median or random_sample_value.</p><p>Step 2: Add a new feature/column to indicate NAN value replaced/not replaced.</p><p>Step 3: Drop the Age column and keep imputed and new importance columns.</p><pre>#1. Add new column with 1 for null values and 0 for not null values<br>DataFrame[&#39;Age_NAN&#39;]=np.where(DataFrame[&#39;Age&#39;].isnull(),1,0)</pre><pre>#2. impute random sample values in Age column - call function<br>impute_random_nan (DataFrame, &#39;Age&#39;)</pre><pre>#Display results<br>DataFrame[[&#39;Age&#39;,&#39;Age_random&#39;,&#39;Age_NAN&#39;]].head(10)</pre><pre>#3. Drop Age Column<br>DataFrame = DataFrame.drop(&#39;Age&#39;,axis=1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*3R3RKk_mCUb0pZvjg1KATg.png" /><figcaption>Index 5: Age NAN value replace with a random value and Age_NAN add 1 to introduce the importance</figcaption></figure><p><strong><em>Advantage:</em> </strong>Capture the importance of missingness.</p><p><strong><em>Disadvantage: </em></strong>Creating Additional Features(Curse of Dimensionality) e.g. if there are 10 columns have null values need to create 10 extra columns.</p><p><strong>4. End of Tail Distribution Imputation</strong></p><p><strong><em>Assumptions:</em></strong> Data is NOT Missing At Random (MAR); Data is skewed at the tail-end.</p><p><strong><em>Description: </em></strong>Take the end tail distribution value (after 3rd std. deviation of distribution curve) and replace NAN/Null values.</p><p><strong><em>Implementation: </em></strong>Handle Age missing values</p><p>Step 1: Get end distribution value, plot distribution of data using the below code:</p><pre># Take non NAN values<br>NonNANData = DataFrame[&#39;Age&#39;].dropna().sample(DataFrame[&#39;Age&#39;].isnull().sum())</pre><pre># Fit a normal distribution to the data:<br>mu, std = norm.fit(NonNANData)</pre><pre># Plot the histogram.<br>plt.hist(NonNANData, bins=50, density=True, alpha=0.6, color=&#39;g&#39;)<br>plt.plot(x, p, &#39;k&#39;, linewidth=2)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Jc7NOQHAQwMsJGXB0H2rIA.png" /></figure><p>Step 2: Take to calculate the average (mean) of extreme values (end tail values) and replace with NAN values</p><pre>#function to impute NAN values with Extreme tail value</pre><pre>def impute_nan_TailValue(DataFrame,variable,ExtremeValue):</pre><pre>    DataFrame[variable+&quot;_end_distribution&quot;] =     DataFrame[variable].fillna(extreme)</pre><pre># Calculate extreme end tail mean value<br>ExtremeEndTailMean = DataFrame.Age.mean()+3*DataFrame.Age.std()</pre><pre># Call funtion to replace NAN values with extreme values<br>impute_nan_TailValue(DataFrame,&#39;Age&#39;,ExtremeEndTailMean)</pre><pre># Display histograms - Data distribution</pre><pre>DataFrame.Age.hist(bins=50, color = &#39;g&#39;)<br>plt.title(&#39;AGE : Normal Distribution Histogram&#39;,fontsize=15)</pre><pre>plt.title(&#39;Age End Distribution : Normal Distribution Histogram&#39;,fontsize=15)<br>DataFrame.Age_end_distribution.hist(bins=50, color = &#39;g&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hGheK8QbDENwajZ7xyZWQQ.png" /><figcaption>Data distribution after imputing NAN values with average end values</figcaption></figure><p><strong><em>Advantage:</em> </strong>Capture the importance of missingness if there.</p><p><strong><em>Disadvantage:</em></strong></p><ul><li>Changes Co-variance/variance i.e distorts the original distribution; may create biased data.</li><li>If the number of NAN values is more then it may mask True outlier values.</li><li>If the number of NAN values is less then replace NAN values may be considered as an outlier.</li></ul><p><strong>5. Arbitrary Imputation</strong></p><p><strong><em>Assumptions:</em></strong> Data is NOT Missing At Random (MAR)</p><p><strong><em>Description: </em></strong>Replacing NAN values with fixed arbitrary value (a random value). The arbitrary value should not frequently occur value in the dataset.</p><p><strong><em>Implementation: </em></strong>Handle Age missing values</p><p>The arbitrary value can be any random value of choice. Sometimes it decided on the basis of domain or system knowledge.</p><p>Here we select 0 and 100 to replace NAN Values.</p><pre># Function to replace NAN values with Arbitary values<br>def impute_nan_ArbitaryValue(df,variable, value):<br>    df[variable+&quot;_&quot;+ str(value)]=df[variable].fillna(value)</pre><pre># Call funtion to replace NAN values with arbitary values<br>impute_nan_ArbitaryValue(DataFrame,&#39;Age&#39;,0)<br>impute_nan_ArbitaryValue(DataFrame,&#39;Age&#39;,100)</pre><pre># Display top 10 data<br>DataFrame[[&#39;Age&#39;,&#39;Age_0&#39;,&#39;Age_100&#39;]].head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*iCKeGfWwYzJa8vf3x-MnJg.png" /><figcaption>Replace NAN values with any random arbitrary value</figcaption></figure><p><strong><em>Advantage:</em> </strong>Capture the importance of missingness.</p><p><strong><em>Disadvantage:</em></strong></p><ul><li>Changes co-variance/variance; may create outliers</li><li>May distort the original distribution of data.</li><li>Hard to decide which value to use.</li></ul><p><strong>Conclusion:</strong></p><p>The above implementation is to explain different ways we can handle missing continuous data. The most widely used methods are Random Sample Imputation and Mean/Median/Mode imputation.</p><p><strong><em>For reference: </em></strong>Jupyter notebook — code available at GitHub: <a href="https://github.com/GDhasade/Medium.com_Contents/blob/master/Handle_Continous_Missing_Data.ipynb">https://github.com/GDhasade/Medium.com_Contents/blob/master/Handle_Continous_Missing_Data.ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4704f52ac9c3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/ways-to-handle-continous-column-missing-data-its-implementations-4704f52ac9c3">Ways to Handle Continous Column Missing Data &amp; Its Implementations</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>