<?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 Oluwabukunmi Ige on Medium]]></title>
        <description><![CDATA[Stories by Oluwabukunmi Ige on Medium]]></description>
        <link>https://medium.com/@oluwabukunmige?source=rss-667aa5802eed------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*Vvl9jhskzI5jmoMoQD5zWw.jpeg</url>
            <title>Stories by Oluwabukunmi Ige on Medium</title>
            <link>https://medium.com/@oluwabukunmige?source=rss-667aa5802eed------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 06:28:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oluwabukunmige/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[Templating your SQL Queries Using Jinga on dbt]]></title>
            <link>https://medium.com/@oluwabukunmige/templating-your-sql-queries-using-jinga-on-dbt-ce3d1e14a7fc?source=rss-667aa5802eed------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce3d1e14a7fc</guid>
            <dc:creator><![CDATA[Oluwabukunmi Ige]]></dc:creator>
            <pubDate>Fri, 12 Nov 2021 22:51:09 GMT</pubDate>
            <atom:updated>2021-11-15T08:41:00.691Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3VKAjagcjVEoKL1B_cRdA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@alanw?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Alan W</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>DBT(data build tool) is a data transformation tool that enables data engineers and analysts to transform and document data. It provides the transformation layer in ELT(export-load-transform) process. It also facilitates how data professionals can build scalable and maintainable code just like software engineers. If you are just coming across DBT for the first time you can check out a more extensive overview on their <a href="https://blog.getdbt.com/what-exactly-is-dbt/">blog</a></p><p>Straight to it, DBT has been quite helpful in my data flow at work and as such, I&#39;d like to document some of the nifty skills I have acquired since I started using the tool.</p><p>For Analysts and Engineers writing maintainable SQL queries can be somewhat of a hassle as we don’t have the benefits to use frameworks or libraries to plug into our queries to ease writing repetitive code. This is where Jinga and DBT comes.</p><p><a href="https://jinja.palletsprojects.com/en/3.0.x/templates/#autoescape-overrides">Jinga</a> is a web templating engine for Python that we can use to write more concise SQL Queries. What DBT helps us achieve is that with Jinga we can bring the functional aspects of programming into our SQL queries to enable us to write easy to maintain queries.</p><p>What we will be covering in this short post is how we can leverage Jinga in DBT to write a concise query that runs and fetches a result that can be used in the final result without using a <a href="https://docs.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-sql?view=sql-server-ver15">CTE</a>(Common table expression).</p><p>To drive home our point I will be using a hypothetical scenario where the data we will be working with contains the dates various commits were made and with which programming language on various open-source projects. I pulled the data from the public datasets in BigQuery and did some trimming to get the data into a format that we could work with. You can access the public data set <a href="https://console.cloud.google.com/marketplace/product/libraries-io?project=delta-sanctum-229711">here</a> and the trimmed version I will be working with <a href="https://docs.google.com/spreadsheets/d/1zKJmHyk9U3lmA2cXSfdtt9AXi4eChX6Lti_LLoWHiUI/edit?usp=sharing">here</a>.</p><p>I will be assuming that you have set up your DBT and have linked your data warehouse to your DBT account. Also that the data we just ingested has been linked as a source on DBT so we can easily query it from DBT.</p><p>for starters, we run a simple query on our data to see if everything is in order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rom0ZiDIqds14nZUnqlE_g.png" /></figure><p>Our data contains 5 columns but our columns of interest are <strong>created_Date</strong> and <strong>language</strong>.</p><p>Let&#39;s find out how many distinct programming languages are in our data set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b8os_pmSYf8oPegUIwbFfQ.png" /></figure><p>There are 12 distinct programming languages in the dataset.</p><p>What we want to achieve is to count the number of times a programming language appears for each day, so we will be grouping by created_Date.</p><p>We will cover how this would be done using normal SQL and elucidate how we can improve our queries using Jinga.</p><p>For our normal Query, we will use a <strong>CASE </strong>statement to set the conditions for each programming language and group the results by Date. The snippet below shows how we went about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I2UFOQDyR1jxNWyaCUrEuQ.png" /></figure><p>Looking at this code we can see how repetitive and stressful writing Queries like this could be, for our case we have 12 distinct languages so we will have to write 12 lines of CASE statements to complete our query. Another issue would be how difficult to maintain this code would be, say there is a new distinct column that has been added to our source data we will have to edit the query to capture the new changes. This would be a less than ideal situation.</p><p>This is where Jinga templating comes in very handy. We can just write a single CASE statement and use Jinga to fill in the distinct languages to make our query concise and easy to maintain.</p><p>To improve on the normal query we will be using the DBT <a href="https://docs.getdbt.com/reference/dbt-jinja-functions/run_query/">run_query</a> macro to run and fetch distinct languages and store as a temporary result so we can make use of it our CASE statements, something like <a href="https://docs.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-sql?view=sql-server-ver15">CTE</a>(common table expression). What this helps us achieve is that even if there are changes in our source data we can run the query against our data source and pull the changes, so it can be in our final query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7GmwDQQ7RiwcZ0pD0YUbXA.png" /></figure><p>The query above flows from stating the temporary Query from our data source to a variable called <strong>program_query </strong>to store the return values of the distinct languages in our data, then we called the <strong>run_query </strong>micro on <strong>program_query</strong> and called it results. Since our results is returning more than one result, we have store the results individually so we can easily loop through it in our final query.</p><p>This helps us to easily access our distinct language results when writing our <strong>CASE</strong> statements. The code snippet below shows us how</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eAJhKsxJYLYaa87nLd_I9Q.png" /></figure><p>Here we can see that the repeated CASE statements have been replaced with a more concise version in the code snippet above.</p><p>Compiling our code returns</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l3SosgUw3Cb7GOofhdd4mw.png" /></figure><p>Now we can see how with less code and some Jinga templating we have been able to achieve the same Query.</p><p>Running our Query returns the results below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eRx74w765_JIxbQusyfi0A.png" /></figure><p>Perfect!!! just as we expected.</p><p><strong>Side note:</strong> In our query above we the clause below was used. What that clause does is that it helps us remove the trailing comma in the last <strong>CASE</strong> statement so our query can run without throwing a compile error. The clause achieves that by looping through the CASE statement and adding a comma to all the <strong>CASE</strong> statements except the last one.</p><pre>{%- if not loop.last -%}</pre><pre>,</pre><pre>{%- endif -%}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7SblqmnFY1gIhJBfXeG6rA.png" /></figure><p>As seen above the last CASE statement doesn’t have a trailing comma.</p><p>There we have it, we have been able to write a full concise and maintainable Query using Jinga templating on DBT.</p><p>I hope this little sneak peak will prompt you to consider exploring Jinga templating your SQL queries.</p><p>You can find the full editable query used in this post <a href="https://carbon.now.sh/?bg=rgba%28171%2C+184%2C+195%2C+1%29&amp;t=vscode&amp;wt=none&amp;l=sql&amp;ds=true&amp;dsyoff=20px&amp;dsblur=68px&amp;wc=true&amp;wa=true&amp;pv=56px&amp;ph=56px&amp;ln=false&amp;fl=1&amp;fm=Hack&amp;fs=14px&amp;lh=133%25&amp;si=false&amp;es=2x&amp;wm=false&amp;code=%250A%257B%2525-%2520set%2520program_query%2520-%2525%257D%250ASELECT%2520distinct%28language%29%2520from%2520%257B%257B%2520ref%28%27stg_programming%27%29%2520%257D%257D%250Aorder%2520by%25201%250A%257B%2525%2520endset%2520%2525%257D%250A%250A%257B%2525%2520set%2520results%2520%253D%2520run_query%28program_query%29%2520%2525%257D%250A%250A%250A%257B%2525%2520if%2520execute%2520%2525%257D%250A%257B%2523%2520Return%2520the%2520first%2520column%2520%2523%257D%250A%257B%2525%2520set%2520results_list%2520%253D%2520results.columns%255B0%255D.values%28%29%2520%2525%257D%250A%257B%2525%2520else%2520%2525%257D%250A%257B%2525%2520set%2520results_list%2520%253D%2520%255B%255D%2520%2525%257D%250A%257B%2525%2520endif%2520%2525%257D%250A%250Aselect%250Acreated_Date%252C%250A%257B%2525-%2520for%2520language%2520in%2520results_list%2520-%2525%257D%250A%257B%2523%2520using%2520a%2520for%2520loop%2520to%2520iterate%2520through%2520each%2520language%2520in%2520the%2520results_list%2520%2523%257D%250A%250ASUM%28CASE%2520WHEN%2520language%2520%253D%2520%27%257B%257Blanguage%257D%257D%27%2520THEN%25201%2520END%2520%29%2520AS%2520%257B%257Blanguage%257D%257D_value%250A%257B%2525-%2520if%2520not%2520loop.last%2520-%2525%257D%250A%252C%250A%257B%2525-%2520endif%2520-%2525%257D%250A%257B%2523%2520each%2520CASE%2520statement%2520has%2520an%2520accompanying%2520comma%2520and%2520if%2520it%2520is%2520the%2520last%2520CASE%2520statement%2520remove%2520the%2520comma%2520%2523%257D%250A%257B%2525%2520endfor%2520%2525%257D%250Afrom%2520%257B%257B%2520ref%28%27stg_programming%27%29%2520%257D%257D%250Agroup%2520by%25201%250A%250A">here</a>. Thanks for the follow through.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce3d1e14a7fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Classes and Object-Oriented Programming(OOP) in Python: A beginner’s Guide]]></title>
            <link>https://medium.com/analytics-vidhya/classes-and-object-oriented-programming-oop-in-python-a-beginners-guide-8105cca6e28b?source=rss-667aa5802eed------2</link>
            <guid isPermaLink="false">https://medium.com/p/8105cca6e28b</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Oluwabukunmi Ige]]></dc:creator>
            <pubDate>Tue, 22 Sep 2020 11:28:53 GMT</pubDate>
            <atom:updated>2020-09-22T13:40:47.883Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J7ElFrZsYT2okBxf18IYOg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@dakotaroosphotography?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Dakota Roos</a> on <a href="https://unsplash.com/s/photos/building-construction?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Classes and OOP is a topic that took me quite a grasp, as such, I had to do a lot digging and extensive reading before I could gain some sort of high-level understanding of the concept; this prompted me to document what I have learnt so far and put out this blog post. The notion is that I want it to serve as a reference when I need to revise the concepts of OOP and also as a guide to beginners who are looking to gain a High-level understanding of Classes and OOP in Python.</p><p>For starters what is Object-Oriented Programming or OOP as it is mostly called? According to Wikipedia OOP is a programming paradigm based on the concept of “objects”, such that it organises software design based around objects in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods.</p><p>OOP in Python employs Classes as it’s the main tool in a coding structure to implement new kind of objects that support inheritance(will be covering this shortly). An object can be defined as a data field in memory that has unique behaviours and OOP focuses on how you can manipulate these objects.</p><p><strong>A high-Level explanation of OOP</strong><br>So far we have covered the basics of OOP but this explanation might not be totally relatable, so let’s see if we can do better by explaining some of the important tenets of OOP using more relatable concepts.</p><p><strong>Composition </strong><br>So imagine the setup of a vehicle, from the engine to its gearbox and say it’s wheels. These are a collection of items working together as a unit to make up the vehicle. For the Vehicle work successfully the engine has to supply power, the wheels enables movement and so on. In OOP lingua this is known as composition and each different component can be coded as a method which will make up the Class of the vehicle.</p><p><strong>Inheritance </strong><br>For inheritance, let’s say our Vehicle is a truck, we are using vehicle because can serve as a generic term for what we are trying to explain. The Sub-class will start off as a Vehicle and the super-class will be that it’s a truck which builds on the features of the vehicle by adding more features. So it starts up a vehicle(which is general) and it inherits the properties of a vehicle in addition to its super-class of being a truck and the truck’s new properties. We can always use the sub-class of a vehicle to buildup other cars like lorries, SUVs et al. This property is known as inheritance and it is one of the main promoting features of OOP. <br>In a High-level Classes are Python Programming units that are compartments for packaging logic and data which a layer of the structure that supports better programming practices such as reusing and customizing code.</p><p><strong>OOP Nomenclature</strong><br>Before we dive into code, let’s explore some OOP nomenclature.</p><p><strong>Object</strong>: An entity that stores data<br><strong>Classes</strong>: Describes an object type by defining what data is stored in the object and what actions can the object perform. It also serves as a factory for generating instances<br>Instances: Describes a specific example of a class. Instances inherit attribute from its class. Each time a class is called, a new instance of that class is generated. Like for our different instances will be different colours of the Class truck.<br><strong>Attribute</strong>: is a variable that belongs to an instance of a class <br><strong>Method</strong>: is a function that belongs to an instance of a class and determines what action the object in the class can perform. The main difference between an attribute and a Method is that an attribute stores data and a method performs an action. Also, methods have parenthesis(), attributes don’t.</p><p><strong>Class Trees</strong><br>Before we explore these features in code, let’s have a breakdown of all the concepts we covered in the previous section. We are going to be elucidating these concepts using a Class Tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lRAt7CRQ0pyFg_x2SKJgJA.jpeg" /><figcaption>A Class tree with 2 instances and 3 Classes</figcaption></figure><p>In the Figure above there are five objects with labelled variables. From bottom-up, we have two instances named Instance 1 and Instance 2 and three classes Class 1, Class 2 and Class 3.<br>Just like we said in the previous section, Classes are factories for generating instances as such an Instance inherits attributes from it’s producing Class and a Class inherits attributes from a Class above it in the tree. As our figure depicts Class 1 C1is the subclass and Classes(C2 &amp; C3) are superclasses. These definitions are based on the relative positions of each Class on the tree. The Class Tree follows a bottom-up flow hence the Superclasses behaviour is shared by all its sub-classes below it in the tree.</p><p>From our Class Tree, say we build-up and instantiate instance I2 with attribute D i.e:<br> I2.D<br>What happens is that an inheritance is effected which triggers a search in the Class tree. Python will search for the attribute D by following the tree path of I2. It follows the path like this:<br>I2, C1,C2,C3 <br>and the search ends at C3 where the attribute D is found. This shows how I2.D maps to C3.D which illustrates that the Instance I2 inherits the attribute D from C3.</p><p>Also, say we want to access the attribute A in instance I1 i.e <br>I1.A <br>What happens here is the search stops at C1.A, as C1 is below C2 and C3 and it overrides them both. As such the attribute A is inherited from C1 into instance I1.</p><p><strong>Coding Class Trees</strong><br>Now let’s piece everything we’ve covered so far using some code. <br>Before that let’s cover some ground truths to aid our understanding.</p><ul><li>A Class is instantiated using the <strong>class</strong> word</li><li>Each class statement generates a new class object and assigns it a name.</li><li>Each time a class is called it generates a new instance object</li><li>Instances are automatically linked to the classes from which they are created</li><li>Classes are automatically linked to their superclasses according to the way they are listed in the parenthesis of the class order i.e from left to right just like our class tree figure depicts.</li></ul><p>To get started with code let’s define a class called <strong>Parent</strong>.<br>Classes are defined just like a function with or without parenthesis and a colon after the class name (():). Also, the body of a class is indented just like that of functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O3N0igOwHf593aW5TPu_gA.jpeg" /></figure><p>The <strong>__init__</strong> method is the constructor method used to initialize the objects’ state. It is automatically called any time an instance of the class is created. The first argument, <strong>self</strong> in the <strong>__init__</strong> method is a special convention in Python representing an object instance. This is because classes are factories for generating multiple instances as such their methods go through this automatically passed self argument anytime we need to fetch or set attributes of the particular instance being processed. So whatever instance that being called is always implied using the <strong>self</strong> argument.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dS0Qch5Tj_tXVMEsx6IYrQ.jpeg" /></figure><p>The code snippet above shows a continuation of the Class we had created above and we added a new method to print whatever argument that the instance receives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tTcqBtxhJ7wvNrs_HBJ4Kg.jpeg" /></figure><p>We created two instances x and y that takes in different arguments a string and an integer. Just as explained above what happens here is that the <strong>self</strong> argument represents whatever instance that is implied, be it x or y and stores the arguments in the instance namespace. So when the display method is called on each instance they both return their respective arguments which show that instances are independent entities despite being created by the same class.</p><p>Now let’s explore the parent-child relationship to make our example more relatable using classes. <br>Next, we are going to add more arguments to the constructor that will store information about a Parent such as last name, eye colour and race. Then we define a new method that displays the argument we received when initiating our Parent class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*rULe2_lSjHnVNN0Gf89TBQ.png" /></figure><p>Let’s create an instance of our Parent class. My name is Bukunmi Ige, so the parent class will be for my Parents, hence I will create an instance with my surname. Then we call the <strong>parent_show_info()</strong> method on our instance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4SryYjaweAZ73wLLWe3swQ.png" /></figure><p>Next let’s create a Child class, which will represent me the Child. This Child class will be a superclass that will inherit arguments from the Parent class which will be the subclass. <br>Now we are creating this Child class based on certain assumptions like The parent and the Child will share some features like Lastname, race and eye colour. The Child class will inherit arguments from the Parent class while also adding its own new arguments. In this case we will be adding cars as the new argument.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HXwgwbpnGtqUfAyluhe5Zg.png" /></figure><p>Then we create an instance of the Child class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*reqEpIx928QMcpG_XSoJ0A.png" /></figure><p>From our instance, we can see that just initiating the Child Class calls both the Child and Parent class.<br>Let’s call the <strong>show_info()</strong> method on our instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IDFBZuk9FZfZ-u6LLHDAEA.jpeg" /></figure><p>By virtue of inheritance, we can access the <strong>parent_show_info() </strong>method to gain information about my parents through our Child instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*5G5qBEwUYTAa5WcizJ7RHg.png" /></figure><p><strong>Conclusion</strong><br>So far so good we covered the important concepts of Python Classes and OOP. We built upon this by exploring a simple but real example of a parent and child relationship to further elucidate these concepts. In the end, we hope this has article given you a high-level introduction to the concept of OOP and classes in Python and hope that it has also gotten you excited to do some more digging on the topic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8105cca6e28b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/classes-and-object-oriented-programming-oop-in-python-a-beginners-guide-8105cca6e28b">Classes and Object-Oriented Programming(OOP) in Python: A beginner’s Guide</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[Scraping Movie Reviews using Beautiful Soup 4 and Python 3]]></title>
            <link>https://medium.datadriveninvestor.com/scraping-movie-reviews-using-beautiful-soup-4-and-python-3-32b0ceeee538?source=rss-667aa5802eed------2</link>
            <guid isPermaLink="false">https://medium.com/p/32b0ceeee538</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Oluwabukunmi Ige]]></dc:creator>
            <pubDate>Tue, 12 Nov 2019 17:55:15 GMT</pubDate>
            <atom:updated>2019-11-23T05:01:58.549Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QEe2Ts6H_h5HkMEk-Pm1Dg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@foxxmd?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Matt Duncan</a> on <a href="https://unsplash.com/s/photos/hills?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Most times, the data you need may not be readily available for download, databases may not be current, and API’s may have usage limits. It is instances like this that web scraping becomes an invaluable skill to possess in your arsenal.</p><p>In this tutorial, we will learn how to scrape reviews of the best movies of all time from <a href="https://www.metacritic.com/">Metacritic.com</a> using Python’s Beautiful Soup and Requests library. We’ll them parse our scraped data into CSV format using Python Pandas library.</p><p><a href="https://www.datadriveninvestor.com/2019/01/23/which-is-more-promising-data-science-or-software-engineering/">Which is More Promising: Data Science or Software Engineering? | Data Driven Investor</a></p><p><strong>Getting Started</strong></p><p>Before we get started with scrapping, a brief introduction to the libraries we will be using, and directions on how to install these libraries on our computer will be explored. The libraries we will be working with are:</p><ol><li>Beautiful Soup:<br>Beautiful Soup is a Python module for extracting information from a web page. You can Install beautiful soup using the python package installer pip or the anaconda package manager conda.</li></ol><pre>pip install BeautifulSoup4 <br>Or<br>conda install BeautifulSoup4Beautiful Soup:</pre><p>2. Requests<br>Requests is a Python library for downloading web pages. The requests library has a get function which we can parse the URL of the site we want to access, and it will download the HTML content of the website. You can install Requests using the code snippet below</p><pre>pip install Requests<br>Or <br>conda install Requests</pre><p>3. Pandas <br>Pandas is a Python library that provides data structures. This is where we will be storing our scraped data. You can install pandas using the code snippet below:</p><pre>pip install pandas</pre><p>Now that we have our dependencies ready, let’s get to Scrapping.</p><p><strong>Identifying the URL Structure<br></strong>The site we will be scraping from is <a href="https://www.metacritic.com/">Metacritic.com</a>. Specifically, we will be extracting the names, release dates, ratings, meta scores and user scores of the best movies on the movie aggregating site.</p><p>Now that our goal is defined, the next port of call get an overview of the web pages and understand the logic of its URL structure. It is pertinent we understand the logic extensively, so we can navigate our way through when we experience a few bumps here and there when developing the scraper.</p><p>Going through Metacritic’s site, we want to scrape information about the best movies of all time on the site. So we go to the movies icon, and from the drop-down list, we select the best movies of all time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N6pBkEtfKESuUXrw" /></figure><p>After selecting the best movies of all time, we arrive at this <a href="https://www.metacritic.com/browse/movies/score/metascore/all/filtered?page=0">URL</a>. Observing the URL, we can see that when switching to the second page on the list, the only parameter that changes is the page number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/0*7XzOacm-7HcJ-j_v" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/0*0orVRLOyOzF9MMnf" /></figure><p>Going by that, we can easily navigate between pages by just changing the page number on the URL of the site. This finding dramatically helps our cause as we only have to write a script that matches the logic of the changes and navigates through all the web pages.</p><p><strong>Parsing the Web Page with Request Library<br></strong>To get started with the script, we can access the contents of a single page using the Requests module. In the code snippet below we will</p><ul><li>Import the get() function from the Requests Library</li><li>We assign headers to the dictionary below. This is to ensure that our requests from our IP address is accepted and not termed as a bot.</li></ul><pre>headers = {‘User-Agent’: ‘Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36’}</pre><ul><li>Pass the URL of the page and the headers dictionary into the get() function and assign it to a variable.</li><li>Get the status_code of the page to see if the page Requests downloaded successfully.</li><li>Print a small part of the Response page HTML tag by accessing the .content attribute.</li><li>Import requests<br>From requests import get<br>movies =</li></ul><pre>get(‘<a href="https://www.metacritic.com/browse/movies/score/metascore/all/filtered?page=0">https://www.metacritic.com/browse/movies/score/metascore/all/filtered?page=0</a>,headers = headers)<br>movies.status_code</pre><pre>200<br># the status_code returns 200 to show that the page was successfully downloaded.</pre><pre>b’&lt;!DOCTYPE html&gt;\n&lt;<strong>html</strong> xmlns:og=”http://opengraphprotocol.org/schema/&quot; xmlns:fb=”http://ogp.me/ns/fb#&quot;&gt;\n&lt;<strong>head</strong>&gt;\n &lt;<strong>title</strong>&gt;Best Movies of All Time — Metacritic&lt;/<strong>title</strong>&gt;\n \n &lt;<strong>meta</strong> http-equiv=”content-type” content=”text/html; charset=UTF-8&quot;&gt;&lt;<strong>script</strong> type=”text/javascript”&gt;window.NREUM||(NREUM={}),<em>__nr_</em>require=function(e,n,t){function r(t){if(!n[t]){var o=n[t]={exports:{}};e[t][0].call(o.exports,function(n){var o=e[t][1][n];return r(o||n)},o,o.exports)}return n[t].exports}if(“function’</pre><p><strong>Understanding the HTML Structure of site’s Pages<br></strong>The first line of the movies.content code snippet from above, we can see that the server returned an HTML document. The document shows us the structure and content of the web page. All the pages we want to scrape poses similar HTML structures which is quite convenient for us, as we only need to understand the structure of one page to build our scrapper.</p><p><strong>Developer Tools</strong> function of the browser provides us access to the HTML structure of a web page. To access the developer tool function, right-click on whatever element you want to examine, select inspect, and it will take you right to the HTML tag of that element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sHLnqLsyvx2BKM2s" /></figure><p>While navigating the HTML tags, we noticed that all the information for each movie is stored inside the &lt;tr&gt; tag and other tags are nested inside the &lt;tr&gt; tag. Each tag can be explored by clicking the grey arrows beside each HTML tag. By breaking down the total nested tags we’d find all the information we need from the selected movie.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M_chEIssQMN_2-vi" /></figure><p><strong>Using Beautiful Soup to Parse the HTML Content</strong></p><p>Next up, we will parse the HTML content of the web page using Beautiful soup. This object will enable us to extract our desired information from the web page. In the following code snippet, we will</p><ul><li>Import Beautiful soup</li><li>Parse the movies.content into the Beautiful Soup object and the ‘html.parser’, assigning the resulting object as movie_soup. The html.parser argument is used because we want our response content parsed by Python’s inbuilt HTML parser.</li></ul><pre>from bs4 import BeautifulSoup<br>laptop_soup = BeautifulSoup(movies.content, ‘html.parser’)</pre><p>As we observed when navigating our HTML tags, all movie information is stored in the &lt;tr&gt; tag. Next, we need to figure out each element’s distinguishing attributes. Most often than not, the distinguishing mark is found in the class attribute. Digging into the &lt;tr&gt; tag, there is another tag &lt;td&gt; with the class value = clamp-summary-wrap. When you hover over this tag, you’d notice that the whole laptop information is been highlighted on the page. This class value is common to all movies on the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EKSxDO2Dk_gC_1mF" /></figure><p>Now let’s use Beautiful Soup’s find_all function to extract all the &lt;li&gt; containers that have a class attribute of:</p><pre>container = laptop_soup.find_all(‘td’, class_ = clamp-summary-wrap)<br>print(type(product))<br>&lt;class ‘bs4.element.ResultSet’&gt;</pre><p>The find_all function returned a ResultSet object that contains all the tags providing information for all the laptops on the page.</p><pre>len(container)<br>100</pre><p>From the len(container) function, we can see that the container captures all the movies by returning 100</p><p><strong>Extracting Data for a Single Laptop<br></strong>Given that all &lt;td&gt; tag is common to all laptops on a page. We will be using a single tag to paint the full picture of the HTML documents for each movie and apply it to all the pages. The tags of the laptop we’d be working with can be accessed using container[1]. The code below shows the first few lines of the HTML document for the first laptop element.</p><pre>&lt;td class=”clamp-summary-wrap”&gt;<br>&lt;input class=”clamp-summary-expand” id=”540575&quot; type=”checkbox”&gt;<br>&lt;div class=”clamp-score-wrap”&gt;<br>&lt;a class=”metascore_anchor” href=”/movie/citizen-kane/critic-reviews”&gt;<br>&lt;div class=”metascore_w large movie positive perfect”&gt;100&lt;/div&gt;<br>&lt;/a&gt;<br>&lt;/div&gt;<br>&lt;span class=”title numbered”&gt;<br> 1.<br> &lt;/span&gt;<br>&lt;a class=”title” href=”/movie/citizen-kane”&gt;<br>&lt;h3&gt;Citizen Kane&lt;/h3&gt;<br>&lt;/a&gt;<br>&lt;div class=”clamp-details”&gt;<br>&lt;span&gt;September 4, 1941&lt;/span&gt;<br>&lt;span class=”cert_rating Approved”&gt; | Approved&lt;/span&gt;<br>&lt;/div&gt;<br>&lt;div class=”summary”&gt;</pre><p>From the HTML tags above, if you look closely you can see some of the information we want to extract which shows we are on the right path. We’d get into digging these HTML tags in the sections below.</p><p><strong>The Name of the Movie<br></strong>The first information we are going to extract is the movie name. To access it’s corresponding HTML document right-click on the element and select inspect to reveal the name’s HTML line. Navigating the HTML lines we can observe that the name is nested inside the &lt;h3&gt; tag.<br>The image below shows the breakdown of all nested tags to the last tag that contains the name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O9FTgJeJqL0kSQ7l" /></figure><p>We accessed the name and specification using the code snippet below:</p><pre>movie = container[1]<br>movie.find(‘h3’).text<br>The Godfather</pre><p><strong>The Date of Release of the Movie<br></strong>We then extract the date of release for the first movie. The data for the release date is nested in a span tag &lt;span&gt; tag contained in a div tag with class value clamp-details. To access these tag we will be making use of the select method from <a href="https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors">CSS SELECTOR</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pwmynEwEb8Re5wI5" /></figure><p>We accessed the release dates using the code snippet below:</p><pre>first_movie.select(‘div.clamp-details span’)[1].text</pre><pre>‘March 11, 1972’</pre><p><strong>The Ratings of the Movie<br></strong>Next, we move on to extract the ratings of the movie. The data for the ratings is also stored in a &lt;span&gt; tag contained in a div tag with a class value of clamp-details.<br>The image below shows the breakdown of all the nested tags to the price of the laptop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yypP62ihX-NI3m8H" /></figure><p>We will also be using the select method from <a href="https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors">CSS SELECTORS</a> to access this information. The select method returns a list, so to access our needed text we have to specify, the number of the item on the list we need.</p><p>The ratings of the laptop are the second item on the list, hence we’d be accessing using number[1]. The code snippet below explains this:</p><pre>first_movie.select(‘div.clamp-details span’)[1].text<br>| R</pre><p><strong>The Metascore<br></strong>Next up we extract the Metascore for the movie. The image below shows the containing tag for the Metascore of the movie</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lDcvp9znbt5TYJ8M" /></figure><p>We accessed the Metascore using the code snippet below:</p><pre>movie.select(‘a.metascore_anchor div’)[0].text<br>100</pre><p><strong>The User Score<br></strong>Finally, we extract information for the user score of the movie. The containing tag for the user is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o6v8w9I2TOSAcV6U" /></figure><p>We accessed the user score using the code snippet below:</p><pre>Movie.select(‘a.metascore_anchor div’)[2].text<br>9.2</pre><p><strong>Building the Script for Multiple Pages<br></strong>Now that we have been able to extract the name, release date, ratings, Metascore and user score for a single movie, the next step is to apply our findings to other pages. The steps below will be highlighting how we are going to build the script for multiple pages.</p><ol><li>Creating a for loop to iterate over all the requests for each page we are scraping from</li><li>Controlling the crawl rate to avoid overwhelming the server with requests</li><li>Monitoring the loop while it runs.</li></ol><p><strong>Creating a for loop to iterate over all the requests for each page we are scraping from<br></strong>Just as we mentioned earlier, each page’s URL follows a certain logic as the web pages change. Hence to make requests we’d have to vary the value of the page parameter. To ease the process we will be creating a loop to iterate over each page. The code block below illustrates this.</p><pre>pages = [str(i) for i in range(1,5)]</pre><p>In the code above, we created a list called pages and ingested it with strings corresponding to the number of pages we are going to scrape.</p><p><strong>Controlling the crawl rate to avoid overwhelming the server with requests<br></strong>It is strongly recommended that we control the crawl rate of our scripts to avoid bombarding the site servers which could result in us having our IP address banned. To prevent this occurrence, we are going to use the sleep() function from python’s time module to pause the execution of the script for a few seconds within intervals.<br>To imitate human behavior, we will vary the amount of waiting time between requests by using the randint() function from python’s random module. randint() would randomly generate integers within a specified interval. An illustration is given in the code snippet below</p><pre>From time import sleep<br>From random import randint<br>sleep(randint(1,4))</pre><p>In the code above the time interval is varied randomly between 1 and 4 seconds.</p><p><strong>Monitoring the loop while it runs.<br></strong>This section is not compulsory, but it can be beneficial for us to know how our script is doing and stop if there are unwanted occurrences.</p><p>First up we import the warn function from the warnings module to notify us if something is off. The code snippet below gives an illustration</p><pre>From warnings import warn <br> if requests &gt; 10:<br>    warn(‘Number of requests was greater than expected.’)</pre><p>The code above would warn us if our requests are greater than 26 and print a warning message.</p><p>Secondly, we create a script to calculate the frequency of our crawler. To calculate the rate, we divide the number of requests by the time elapsed since the first request. The code snippet below gives an illustration.</p><p>In the code block below, we imported the clear_output function from Ipython’s core.display module. The clear_output function is set to True to clear the current output of the frequency calculations for a new one to appear.</p><p>In the frequency calculator we:</p><ul><li>Set the requests to zero and increment it by one for each request</li><li>Calculate the elapsed time since the first request and assign it to elapsed time</li><li>Print the number of requests and frequency</li><li>Clear the output for the next frequency calculation.</li></ul><pre>From Ipython.core.display import clear_output<br>Start_time = time()<br>requests = 0<br>requests += 1<br> <br>elapsed_time = time() — start_time<br>print(‘Request:{}; Frequency: {} requests/s’.format(requests, requests/elapsed_time))<br>clear_output(wait = True)</pre><p><strong>The Full Script<br></strong>Now let’s compute the full script. The steps below explain every part of the final code.</p><ul><li>Creating empty lists to store the scraped data</li><li>Initialising the monitoring loop</li><li>Loop through pages list to vary the page parameter of the URL</li><li>Pass the pages into the GET requests to iterate over each page.</li><li>Pause the time interval between 8 and 20 seconds</li><li>Monitor each request</li><li>Give a warning for a non 200 status_code</li><li>Convert the response HTML to a Beautiful Soup Object</li><li>Extract the laptop names and prices from the Beautiful Soup object and append them into their respective lists</li><li>Parse the data into a Pandas data frame and store it in a CSV file</li></ul><p>The full code block can be accessed <a href="https://oluwabukunmige.github.io/Web-scrapping/">here</a></p><p><strong>Parsing the data into a Dataframe and storing into a CSV File<br></strong>Finally, we parse the scraped data into a pandas data frame to enable us to save as a CSV file.<br>To do this, we import the Pandas module and pass the lists we just scraped into a dictionary. Each key in the dictionary will form the column of the data frame.</p><pre>import pandas as pd<br>movie_df = pd.DataFrame({‘Movie_names’: names,<br>‘Release_dates’: release_dates,<br>‘Ratings’: ratings,<br>‘Meta_scores’: meta_scores,<br>‘User_scores’: user_scores})<br>print(movie_df.info())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gQW8mp6oZTQQyCzZ" /></figure><p>Crosschecking our scraped data with the information on the site, we can see that we are on the right track as the first 100 movies are the same with ones on the site.</p><p>We then store the resulting data frame into a CSV file.</p><pre>movie_df.to_csv(‘movies.csv’)</pre><p><strong>Conclusion</strong></p><p>There you have it, we have successfully extracted ratings of the best movies of all time from <a href="https://www.metacritic.com/">Metacritic</a> and saved it into a CSV file. You can access the full code snippet <a href="https://github.com/Oluwabukunmige/Web-Scrappers/blob/master/Movie%20Reviews%20using%20Beautiful%20Soup">here</a>. You can always try your hands on similar projects and can also modify the code to suit your needs.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb2a0d6%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2Fb2a0d6%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href">https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32b0ceeee538" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/scraping-movie-reviews-using-beautiful-soup-4-and-python-3-32b0ceeee538">Scraping Movie Reviews using Beautiful Soup 4 and Python 3</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to extract information from your excel sheet using Python]]></title>
            <link>https://medium.com/analytics-vidhya/how-to-extract-information-from-your-excel-sheet-using-python-5f4f518aec49?source=rss-667aa5802eed------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f4f518aec49</guid>
            <category><![CDATA[python-data-analysis]]></category>
            <category><![CDATA[python-data-science]]></category>
            <category><![CDATA[python-web-developer]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Oluwabukunmi Ige]]></dc:creator>
            <pubDate>Sat, 31 Aug 2019 16:54:28 GMT</pubDate>
            <atom:updated>2019-09-29T13:26:17.996Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zXZJcDBWsOLxMLKBRhedgA.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/freephotocc-2275370/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1280558">Andrian Valeanu</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1280558">Pixabay</a></figcaption></figure><p>One of the fascinating things about programming is that with a few lines of code you can get your computer to carry out a task that would have been otherwise mundane and annoying for you to do on your own. One of those mundane tasks is extracting information from a large excel sheet. The Python programming language is very robust, and one of the areas where it shines is helping us automate tedious and repetitive Excel tasks.</p><p>In this blog post, we will be embarking on a step by step process to extract some valuable information from an excel sheet. The excel sheet we will be using is the sheet that contains all the fruit sales of a supermarket for a month. Each row contains individual records of fruits purchased by customers. There are three columns in the excel sheet. Column A gives the cost per pound of the purchased fruit, Column B gives the Pounds sold, and Column C gives us the total cost of the purchase. The excel sheet has 23758 rows and four columns. You can download the excel sheet <a href="https://drive.google.com/open?id=1cyNI4BKBBQvcVVsQgiiQFoCKRm0zeqwX">here</a>.</p><p>Our goal is to find out and document the total pounds sold total sales and the entire purchase instances for each fruit in that month. You can imagine the frustration of having to go through 23758 rows to extract information about each fruit, well we are in luck as Python would help us to complete this task in no time. The steps below will give an in-depth and practical explanation of how you can use Python to complete this task.</p><p>Before we get on to this task, I want to assume that you have a basic knowledge of writing code in Python and that you have the Python installed on your computer.</p><p><strong>Install the openpyxl Module<br></strong>The python module we will be working with is the OpenPyXL Module. The OpenPyXL Module is a library that allows you to use Python to read and write excel files or files with the .xlsx/xlsm/xltx/xltm extension. If you don’t have it installed on your IDE, you can install it using</p><pre>pip install openpyxl</pre><p>To test if you successfully installed it, import it using</p><pre>Import openpyxl</pre><p>So far no error is returned you have installed the OpenPyXL Module and are ready to work on some excel documents.</p><p><strong>Read in and open the Excel document with OpenPyXL<br></strong>The next port of call is to read in the excel sheet into our Python environment. Make sure the Excel you will be working with is in your current working directory(CWD). You can access your CWD using:</p><pre>import os <br>os.getcwd()</pre><pre>os.chdir() #this changes our CWD, if the excel sheet is not in CWD</pre><p>What if the excel sheet is not in your CWD? You can copy the file and paste it into your CWD, so you access it from there. Once we are sure we have our Excel document in our CWD, we can now read it in.<br>After reading in the Excel document, we can now access it to obtain various information about the excel sheet.</p><pre>import pandas as pd <br>file = ‘produceSales.xlsx’<br>data = pd.ExcelFile(file)<br>print(data.sheet_names) #this returns the all the sheets in the excel file<br>[‘Sheet1’]</pre><p>Next, we parse the sheet we will be working with into a data frame, this will enable us to know if our excel sheet was correctly read in.</p><pre>df = data.parse(‘Sheet1’)<br>df.info</pre><pre>df.head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/0*TYZ7L4lArXqn-RiE" /><figcaption>This image shows the first ten rows of our sheet.</figcaption></figure><p><strong>Read in the spreadsheet data<br></strong>The next step is to read in data from the spreadsheet [Sheet1].</p><pre>ps = openpyxl.load_workbook(‘produceSales.xlsx’)</pre><pre>sheet = ps[‘Sheet1’]</pre><pre>sheet.max_row <br>#returns the total number of rows in the sheet<br>23758</pre><p>Next, we use a For loop to iterate over all the rows in the sheet.</p><pre>for row in range(2, sheet.max_row + 1):</pre><pre># each row in the spreadsheet represents information for a particular purchase.</pre><pre>produce = sheet[‘B’ + str(row)].value</pre><pre>cost_per_pound = sheet[‘C’ + str(row)].value</pre><pre>pounds_sold = sheet[‘D’ + str(row)].value</pre><pre>total_sales = sheet[‘E’ + str(row)].value</pre><pre># the first column is B followed by C and so on.</pre><pre># Each value in a cell is represented by a column letter and a row number. So #the first element in the sheet is B1, next column C1 and so on. This enables #to iterate over the entire cells.</pre><p>Create an empty dictionary that contains all the information on each fruit. We then use the set.default() method to fill the first set of elements into the dictionary. set.default() first argument checks if the key exists in the dictionary, if it doesn’t it replaces it with the second argument. That way, we can start populating our dictionary with the second argument of the set.default function.</p><pre>TotalInfo.setdefault(produce,{‘Total_cost_per_pound’: 0,<br> ‘Total_pounds_sold’: 0, <br> ‘Total_sales’: 0,<br> ‘Total_Purchase_Instances’: 0})</pre><pre># so with this set default method, we have set all metrics we want to collect to zero. When we are iterating, we start from Zero and add new iterated to the dictionary. The key of the dictionary is the fruit which is mapped to their various metrics.</pre><p>Finally, we populate the dictionary. For each new produce seen in a new row, we increase the metric by its corresponding value in the new row.</p><pre># Each row represents a fruit, so increment by the new corresponding values. <br> <br> TotalInfo[produce][‘Total_cost_per_pound’] += float(cost_per_pound)</pre><pre>TotalInfo[produce][‘Total_pounds_sold’] += int(pounds_sold)<br> <br> TotalInfo[produce][‘Total_sales’] += int(total_sales)</pre><pre># Each row represents a fruit, so increment by one. <br> <br> TotalInfo[produce][‘Total_Purchase_Instances’] += 1</pre><p>After running this code block, we would have populated the TotalInfo dictionary with all the various metrics for each fruit for the month. The populated dictionary looks like this:</p><pre>‘Apples’: {‘Total_Purchase_Instances’: 627,<br> ‘Total_cost_per_pound’: 1178.7600000000068,<br> ‘Total_pounds_sold’: 12119,<br> ‘Total_sales’: 22999},</pre><p><strong>Write the Results to a File<br></strong>After populating the TotalInfo dictionary. We can write this populated dictionary to any file of our choice be it a .csv, .txt, .py et al. We will be using the pprint.pformat module to pretty print our dictionary’s values and we use python’s write mode to write the dictionary’s values to the file. The code snippet below gives an illustration:</p><pre>resultFile = open(‘Total_info.txt’, ‘w’)<br>resultFile.write(pprint.pformat(TotalInfo))<br>resultFile.close()<br>print(‘Done.’)</pre><p>The Total_info.txt file will be found in your CWD. <br>You can always change the file format by changing the .txt extension to whatever file format you want. <br>The code snippet below shows how you can change to a .csv file format.</p><pre> Open (‘Total_info.csv’, ‘w’)</pre><p><strong>Conclusion<br></strong>In this blog post, we demonstrated how we could use Python to extract information from an excel sheet. Knowing how to obtain information from an excel sheet is always a welcome addition to your toolbox as it saves you a lot of time from carrying out repetitive tasks. Feel free to modify the code in the article to suit your needs; you can access the notebook that contains the end to end code that was used in this blog post <a href="http://github.com/Oluwabukunmige/Working-with-Excel-Sheets">here</a>.</p><p>Happy Pythoning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f4f518aec49" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/how-to-extract-information-from-your-excel-sheet-using-python-5f4f518aec49">How to extract information from your excel sheet using Python</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[Selective Copying of Files from One Folder to Another using Python]]></title>
            <link>https://medium.com/@oluwabukunmige/selective-copying-of-files-from-one-folder-to-another-using-python-346ad1f500fa?source=rss-667aa5802eed------2</link>
            <guid isPermaLink="false">https://medium.com/p/346ad1f500fa</guid>
            <category><![CDATA[python-hacks]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Oluwabukunmi Ige]]></dc:creator>
            <pubDate>Thu, 08 Aug 2019 16:18:01 GMT</pubDate>
            <atom:updated>2019-08-08T16:18:01.505Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJ9yeMAAqwDP_7RBVGcdMw.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/Pexels-2286921/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1866598">Pexels</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1866598">Pixabay</a></figcaption></figure><p>I am a big fan of finding easier and faster ways of doing things and as such whenever I come across a new trick or hack, I am always excited. Recently, I was able to use Python to selectively copy a bunch of files with the same file extension from one folder to another and was really thrilled because I knew such a task could be really daunting especially if you have a lot of files to copy from folder to folder.</p><p>In this blog post, I will be giving a short explanation of how you can use python to selectively copy files from one folder to another on your computer. o follow through and implement this task, it is necessary for you to have Python installed on your computer. You can always implement the code snippets from your Command Prompt or your IDE.</p><p>We will be using Python’s OS and the shutil (Shell Utilities) module. The OS module allows you to interact with your operating system and make use of your operating system’s dependent functionality while the Shutil module enables you to copy, move, delete or rename files on your computer.</p><p>The steps to achieve this goal are annotated below:</p><p>First, <strong>Import all needed dependencies</strong></p><p>The first step is to import all our needed dependencies which are OS and Shutil.</p><pre>import os<br>import shutil</pre><p>If it returns a no module name error, you can always install the dependencies using</p><pre>pip install shutil</pre><p>After importing all dependencies we are good to go.</p><p>Next, <strong>Obtain File Paths for both Folders</strong></p><p>We obtain the file paths for the folder we want to copy from and the folder we want to copy to.</p><p>So what is a file path? A file path is a string value that tells you the location of a file or folder in your computer. It usually looks like this:</p><pre>&#39;/home/oluwabukunmi/Python Book&#39;   # for Linux and OSX </pre><pre>&#39;C:\Windows\oluwabukunmi\Python Book   #For Windows</pre><p>The path is from the root directory which is ‘/home/oluwabuknmi’ to ‘/Python Book’ which is the Basename or for this case our Folder name.</p><p>So we can easily obtain the File path of our folders by following the trail of our file from the root directory to the basename. For instance, let’s say our files are stored in a Python Book subfolder under the Books folder our file path will be :</p><pre>&#39;/home/oluwabukunmi/Books/Python Book&#39;</pre><p>For our instance, the file path for our source folder is:</p><pre>&#39;/home/oluwabukunmi/Python Book/Python Files&#39;</pre><p>The file path of the file we’d be copying to:</p><pre>&#39;/home/oluwabukunmi/Python Book/CSV Files&#39;</pre><p><strong>Copy the Files</strong></p><p>The next step is copying the files from our source to our destination folder. But first, we need to ingest both our source and destination file paths.</p><p>We use the input() function to ingest our file paths. The input function will read in our file path converts it as a string and returns it. So ensure you remove the parentheses from your file path before you enter it into the input function.</p><pre>source_folder = input(/home/oluwabukunmi/Python Book/Python Files)</pre><pre>#this code takes in the file path of our source folder</pre><pre>destination_folder = input(/home/oluwabukunmi/Python Book/CSV Files)</pre><pre>#this code takes in the file path of our destination folder</pre><p>Next up is the file extension of the files we want to copy, in this case, we want to copy CSV files from our source to the destination. We also ingest it using the input() function.</p><pre>extension = input(.csv)</pre><p>You can always change this extension to whatever format you want, be it .pdf, .xlml,.mp3 et al. you are only limited by your mind.</p><p>Finally, we copy the files from our source_folder to the destination folder. The code to implement is given below:</p><pre>for folders, subfolders, filenames in os.walk(source_folder):</pre><p>we use the os.walk function to move from the folders to the subfolder and to the file name.</p><pre>for filename in filenames:</pre><p>We iterate over all the filenames our source folder</p><pre>if filename.endswith(‘{}’.format(extension)):<br>   shutil.copy(os.path.join(folders, filename), destination_folder)</pre><p>the {} sign serves as a placeholder for each file name before the file extension. <br>We then use the shutil.copy command to finally copy the files.</p><p>We can also move files using shutil.move if duplicate files are not needed.</p><pre>shutil.move(os.path.join(folders, filename), destination_folder)</pre><p>There you have it, we have been able to successfully copy or move files from one folder to another with a few lines of Python code, I hope this was helpful… Feel free to modify the code to suit your needs.</p><p>You can access the end to end code snippet used in the blog post here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=346ad1f500fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logistic Regression in SciKit Learn, A step by step Process]]></title>
            <link>https://medium.com/@oluwabukunmige/logistic-regression-in-scikit-learn-a-step-by-step-process-32f546241f32?source=rss-667aa5802eed------2</link>
            <guid isPermaLink="false">https://medium.com/p/32f546241f32</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <dc:creator><![CDATA[Oluwabukunmi Ige]]></dc:creator>
            <pubDate>Thu, 01 Aug 2019 09:54:11 GMT</pubDate>
            <atom:updated>2019-09-24T11:45:22.112Z</atom:updated>
            <content:encoded><![CDATA[<p>Logistic Regression is a classification algorithm that is used to predict the probability of a categorical dependent variable. It is a supervised Machine Learning algorithm. Despite being called Logistic Regression is used for classification problems. The decision boundary of logistic regression is a linear binary classifier that separates the two classes we want to predict using a line, a plane or a hyperplane.</p><figure><img alt="Image by &lt;a href=”https://pixabay.com/users/DariuszSankowski-1441456/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp" src="https://cdn-images-1.medium.com/max/1024/1*l6XKtn_CIozUILD2I4FHPA.jpeg" /></figure><p><strong>Implementation<br></strong>Scikit Learn has a Logistic Regression module which we will be using to build our machine learning model. The dataset we will be training our model on is <a href="http://kaggle.com/sarahvch/predicting-who-pays-back-loans?source=post_page---------------------------#loan_data.csv">Loan data from the US Lending Club</a>. A brief description of the dataset was given in our previous blog post, you can access it <a href="http://medium.com/@oluwabukunmige/my-machine-learning-journey-249a3a0729f9">here</a>.</p><p>Our goal is to determine if predict if a customer that takes a loan will payback. The model will predict(1) if the customer defaults in paying and (0) if they repay the loan.</p><p><strong>Read in the dataset<br></strong>Our first point of call is reading in the data, let&#39;s see if we have any missing values.</p><pre>import pandas as pd<br>loan = pd.read_csv(‘loan.csv’)</pre><pre>final_loan = loan.copy()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*WfszRE432kFiXEVxdGOKMQ.jpeg" /></figure><p>wow, good news our data seems to be in order. Our target variable is not.fully.paid column. Where 1 means the customer defaulted the loan and 0 means they paid back their loans.</p><p><strong>Preprocessing<br></strong>We will be using the Pipeline module from Sci-kit Learn to carry out our preprocessing steps. Pipelines allow us to chain our preprocessing steps together with each step following the other in sequence. Pipelines help keep our code tidy and reproducible.</p><p>Before we begin preprocessing, let&#39;s check if our target variable is balanced, this will enable us to know which Pipeline module we will be using.</p><pre>target_count = final_loan[&#39;not.fully.paid&#39;].value_counts(dropna = False)</pre><pre>target_count<br>0    8045 <br>1    1533</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*DbQTivmhzMgGCmss3tdNww.jpeg" /></figure><p>From the image and code snippet above we can see that our target variable is greatly imbalanced at a ratio 8:1, our model will be greatly disadvantaged if we train it this way. We going to oversample the minority class using the SMOTE algorithm in Scikit-Learn.<br>So what does this have to do with the Pipeline module we will be using you say? the SMOTE(synthetic minority oversampling technique) algorithm can&#39;t be implemented with the normal Pipeline module as the preprocessing steps won’t flow. Luckily for us, Scikit-Learn has a Pipeline function in its imbalance module.</p><pre>from imblearn.pipeline import Pipeline</pre><p>Next, up we import all needed modules including the column Transformer module which helps us separately preprocess categorical and numerical columns separately.</p><pre>from sklearn.compose import ColumnTransformer<br>from sklearn.preprocessing import PolynomialFeaturesfrom sklearn.linear_model  import LogisticRegression<br>from sklearn.preprocessing import StandardScaler, OneHotEncoder<br>from imblearn.over_sampling import SMOTE<br>from imblearn.pipeline import Pipeline<br>from sklearn.model_selection import train_test_split</pre><p>We preprocess the numerical column by applying the standard scaler and polynomial features algorithms.</p><pre>numeric_features = [&#39;credit.policy&#39;,&#39;int.rate&#39;,<br>                    &#39;installment&#39;,&#39;log.annual.inc&#39;,&#39;dti&#39;,&#39;fico&#39;,<br>                    &#39;days.with.cr.line&#39;,&#39;revol.bal&#39;,&#39;revol.util&#39;,<br>                    &#39;inq.last.6mths&#39;,&#39;delinq.2yrs&#39;,&#39;pub.rec&#39;]</pre><pre>numeric_transformer = Pipeline(steps=[(&#39;poly&#39;,PolynomialFeatures(degree = 2)),<br>                                      (&#39;scaler&#39;, StandardScaler())])</pre><p>We preprocess the categorical column by one hot-encoding it.</p><pre>categorical_features = [&#39;purpose&#39;]</pre><pre>categorical_transformer = Pipeline(steps=[<br>    (&#39;onehot&#39;, OneHotEncoder(handle_unknown=&#39;ignore&#39;))])</pre><p>Combine both numerical and categorical column using the Column Transformer module</p><pre>preprocessor = ColumnTransformer(<br>    transformers=[<br>        (&#39;num&#39;, numeric_transformer, numeric_features),<br>        (&#39;cat&#39;, categorical_transformer, categorical_features)])</pre><p>Define the SMOTE and Logistic Regression algorithms</p><pre>smt = SMOTE(random_state=42,ratio = &#39;minority&#39;)<br>lor = LogisticRegression(C = 50)</pre><p>Chain all the steps using the imbalance Pipeline module</p><pre>clf = Pipeline([(&#39;preprocessor&#39;, preprocessor),(&#39;smt&#39;, smt),<br>                (&#39;lor&#39;,lor)])</pre><p>Split the data into train and test folds and fit the train set using our chained pipeline which contains all our preprocessing steps, imbalance module and logistic regression algorithm.</p><pre>y = final_loan[&#39;not.fully.paid&#39;]<br>X = final_loan.drop(&#39;not.fully.paid&#39;, axis = 1)</pre><pre>X_train, X_test, y_train, y_test = train_test_split(X, y,random_state = 50 )</pre><pre>clf.fit(X_train, y_train)</pre><p>We gain intuition into how our model performed by evaluating accuracy.</p><pre>clf.score(X_train, y_train)<br>0.6384519003202005</pre><pre>clf.score(X_test, y_test)<br>0.6125260960334029</pre><p>From this score, we can see that our model is not overfitting but be sure to take this score with a pinch of salt as accuracy is not a good measure of the predictive performance of our model.</p><p><strong>Confusion Matrix<br></strong>Confusion matrix gives a more in-depth evaluation of the performance of our machine learning module. It gives us an idea of the number of predictions our model is getting right and the errors it is making.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*Z54JgbS4DUwWSknhDCvNTQ.png" /></figure><p>The result of the confusion matrix of our model is shown below:</p><pre>from sklearn.metrics import confusion_matrix<br>from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score<br>from sklearn.metrics import classification_report</pre><pre>confusion = confusion_matrix(y_test, clf_predicted)<br>confusion</pre><pre>array([[1247,  785],      <br>      [ 143,  220]])</pre><p>From our conclusion matrix, we can see that our model got (1247+220) 1467 predictions right and got (143+785) 928 predictions wrong. Let’s find out more from our classification report</p><p><strong>Classification Report<br></strong>Shows the precision, recall and F1-score of our model.</p><pre>from sklearn.metrics import classification_report</pre><pre>print(classification_report(y_test, clf_predicted, target_names=[&#39;0&#39;, &#39;1&#39;]))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*dslLA51ZvgOJfNh7Fb3wvA.jpeg" /></figure><p><strong>Interpretation: </strong>From our classification report we can see that our model has a Recall rate of has a precision of 22% and a recall rate of 61%, Our model is not doing too well.</p><p>From the confusion Matrix, we have 785 false positives. This means that our model predicted that 785 people won’t pay back their loans whereas these people actually paid. This is actually bad for business because we will be turning down people that can actually pay back their loans which will mean losing a huge percentage of our potential customers.<br>Our model also has 143 false positives. What this means is that our model predicted that these 143 will pay back their loans, whereas they didn’t. This is also bad for business as we don’t want to be approving loans to folks that would abscond that would mean an automatic loss.</p><p><strong>ROC Curve<br></strong>The ROC curve shows the false positive rate(FPR) against the True Positive rate (TPR). The code snippet below implements it.</p><pre>import sklearn.metrics as metrics</pre><pre># calculate the fpr and tpr for all thresholds of the classification<br>probs = clf.predict_proba(X_test)</pre><pre>preds = probs[:,1]</pre><pre>fpr, tpr, threshold = metrics.roc_curve(y_test, preds)<br>roc_auc = metrics.auc(fpr, tpr)</pre><pre><br>import matplotlib.pyplot as plt<br>plt.title(&#39;Receiver Operating Characteristic&#39;)<br>plt.plot(fpr, tpr, &#39;b&#39;, label = &#39;AUC = %0.2f&#39; % roc_auc)<br>plt.legend(loc = &#39;lower right&#39;)<br>plt.plot([0, 1], [0, 1],&#39;r--&#39;)<br>plt.xlim([0, 1])<br>plt.ylim([0, 1])<br>plt.ylabel(&#39;True Positive Rate&#39;)<br>plt.xlabel(&#39;False Positive Rate&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*yDxxrfYKQuH266Fz-IhqwQ.jpeg" /></figure><p>The ideal ROC curve would be at the top left-hand corner of the image at a TPR of 1.0 and FPR of 0.0, our model is quite above average as it’s above the basic threshold which is the red line. We have an Area Under the Curve(AUC) of 66%.</p><p>The Logistic Regression model we trained in this blog post will be our baseline model as we try other algorithms in the subsequent blog posts of this series. Hopefully, we attain better Precision, recall scores, ROC and AUC scores.</p><p>The Google Colaboratory notebook used to implement the Logistic Regression algorithm can be accessed <a href="https://github.com/Oluwabukunmige/My-Machine-Learning-Journey/blob/master/Machine_Learning_Algorithths.ipynb">here</a>.</p><p>Thank you for your time, feedback and comments are always welcomed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32f546241f32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Linear Regression with Sci-kit Learn.]]></title>
            <link>https://medium.com/@oluwabukunmige/implementing-linear-regression-with-sci-kit-learn-b6f87edc3150?source=rss-667aa5802eed------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6f87edc3150</guid>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[linear-regression-python]]></category>
            <dc:creator><![CDATA[Oluwabukunmi Ige]]></dc:creator>
            <pubDate>Tue, 09 Jul 2019 16:41:07 GMT</pubDate>
            <atom:updated>2019-07-17T16:26:15.578Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementing Linear Regression with ColumnTransformer on Sci-kit Learn.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PcTu-jNSmwxr82jdEEGtiQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Markus Spiske</a></figcaption></figure><p>In this blog post, I will be giving a step by step explanation on the implementation of Linear Regression with Sci-kit Learn.<br>In a regression problem, the goal is to use a predict a continuous target variable using mathematical functions. Linear regression models a linear relationship between the input features and the continuous target variable.</p><p>Sci-Kit learn has a linear regression module that makes it easy to implement the algorithm on your data. The data I will be using is the <a href="https://www.kaggle.com/camnugent/california-housing-prices">California Housing Prices</a> dataset. I gave a brief explanation of the data in my previous blog post you can access it <a href="http://medium.com/@oluwabukunmige/my-machine-learning-journey-249a3a0729f9">here</a>. The goal is to predict the housing prices of California from the features in the dataset.</p><p><strong>Read in the data <br></strong>The first step is to read in our data and preprocess it before ingesting into the linear regression model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*A0nPCToImnDvH-EyQM8-PQ.png" /></figure><p>From the info above can see that the total_bedrooms column has some missing values. I missing values was filled with the total_bedroom median value.</p><pre>final_housing[‘total_bedrooms’].fillna(final_housing[‘total_bedrooms’].median(), inplace = True)</pre><p><strong>Why Column Transformer?<br></strong>Column transformer is a module in Scikit-Learn that allows us to perform different preprocessing and feature extraction steps on features of different data types. Our dataset, for instance, contains both continuous and categorical features, these two data types require different preprocessing steps. Categorical features require one-encoding, continuous features requires standard scaling, the Column Transformer makes it possible to apply these preprocessing steps to these features. The pipeline module will then be used in integrating the preprocessed features, which will be used in building our Linear Regression model.</p><p><strong>Preprocessing our data<br></strong>The code scripts below will be showing how to use the Column Transformer and Pipeline module on our dataset.</p><pre># Import all needed modules<br>from sklearn.compose import ColumnTransformer<br>from sklearn.pipeline import Pipeline<br>from sklearn.preprocessing import PolynomialFeatures<br>from sklearn.preprocessing import StandardScaler, OneHotEncoder<br>from sklearn.linear_model import LinearRegression<br>from sklearn.model_selection import train_test_split</pre><p>Preprocess the Numeric columns<br>We apply PolynomialFeatures and StandardScaler preprocessing steps to the numeric columns.</p><pre>numeric_features = [&#39;longitude&#39;,&#39;latitude&#39;,&#39;housing_median_age&#39;,<br>                    &#39;total_rooms&#39;,&#39;total_bedrooms&#39;,<br>                    &#39;population&#39;,&#39;households&#39;,&#39;median_income&#39;]</pre><pre>numeric_transformer = Pipeline(steps=[(&#39;poly&#39;,PolynomialFeatures(degree =2)),<br>                                      (&#39;scaler&#39;, StandardScaler())])</pre><p>Preprocess the Categorical Column<br>We one-hot encode our categorical data</p><pre>categorical_features = [&#39;ocean_proximity&#39;]</pre><pre>categorical_transformer = Pipeline(steps=[<br>    (&#39;onehot&#39;, OneHotEncoder(handle_unknown=&#39;ignore&#39;))])</pre><p>Combine the two preprocessed steps together using the Column Transformer module</p><pre>preprocessor = ColumnTransformer(<br>    transformers=[<br>        (&#39;num&#39;, numeric_transformer, numeric_features),<br>        (&#39;cat&#39;, categorical_transformer, categorical_features)])</pre><p><strong>Integrate the Preprocessed Features and Linear Regression Model Using Pipelines<br></strong>The next step is the integrate the features we just preprocessed with our Machine Learning algorithm to enable us to build a model</p><pre>clf = Pipeline(steps=[(&#39;preprocessor&#39;, preprocessor),<br>                      (&#39;classifier&#39;, LinearRegression())])</pre><p><strong>Train our Model</strong></p><pre>X = final_housing.drop(&#39;median_house_value&#39;, axis = 1)<br>y = final_housing[&#39;median_house_value&#39;]</pre><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 0)</pre><pre>clf.fit(X_train, y_train)</pre><p><strong>Evaluate the trained model</strong></p><pre>clf.score(X_train, y_train)</pre><pre>0.7012750467393345</pre><p>Our model gives us 70.13% accuracy.<br>Let see how our model does on the test set.</p><pre>clf.score(X_test, y_test)</pre><pre>0.6954375277548792</pre><p>Our model gives us 69.54% on the test set.</p><p>From these metrics, we can see that our model is not overfitting, so there’s no need to apply any regularisation techniques to it. Let’s if our model will perform better when we increase the degree of our Polynomial features.</p><pre>numeric_features = [&#39;longitude&#39;,&#39;latitude&#39;,&#39;housing_median_age&#39;,&#39;total_rooms&#39;,&#39;total_bedrooms&#39;,&#39;population&#39;,&#39;households&#39;,&#39;median_income&#39;]</pre><pre>​numeric_transformer = Pipeline(steps=[(&#39;poly&#39;,PolynomialFeatures(degree =3)),<br>(&#39;scaler&#39;, StandardScaler())])</pre><p>This is the only preprocessing step that is changed every other step remains the same.</p><pre>clf.score(X_train, y_train)</pre><pre>0.7443783826983932</pre><pre>clf.score(X_test, y_test)</pre><pre>0.673920805975633</pre><p>Our train score improves to 74.3% but our test score drops to 67.3%, which is an indication that our model is overfitting our training data. Hence Polynomial features at degree = 2, performs best on both train and test data.</p><p>Linear regression with polynomial features of degree 2 gives us the best accuracy score of roughly 70% on both the train and test datasets. In the subsequent blog posts of these series, other algorithms will be tried and hopefully, we can achieve higher accuracy.</p><p>You can access the notebook used in this blog post <a href="http://github.com/Oluwabukunmige/My-Machine-Learning-Journey/blob/master/Regression.ipynb">here</a>. <br>You can always relay your thoughts and comments in the comment section. Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6f87edc3150" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Machine Learning Journey]]></title>
            <link>https://medium.com/@oluwabukunmige/my-machine-learning-journey-249a3a0729f9?source=rss-667aa5802eed------2</link>
            <guid isPermaLink="false">https://medium.com/p/249a3a0729f9</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Oluwabukunmi Ige]]></dc:creator>
            <pubDate>Tue, 02 Jul 2019 11:41:31 GMT</pubDate>
            <atom:updated>2019-07-30T15:33:57.802Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*DcWigmZDCS56AbMzkzcxyQ.jpeg" /></figure><p>This will be a series of blog posts where I will be implementing all the machine learning algorithms I have learnt so far. Each blog post will be peculiar to different algorithms and I will preprocessing the datasets used to ensure each algorithm used performs well enough. This series will be focused on Supervised Learning, both classification and regression problems will be covered. An overview of the datasets that will be using during the course of this series is given below:</p><p><strong>Classification: </strong><br>For the classification problem, the dataset that will be used is the loan data from the lending club. The lending club is a US peer-peer lending company that enables borrowers to create unsecured personal loans between $1,000 and $40,000. Our goal is to predict if a customer will pay back his/her loan.<br>The data is from 2007–2010. You can access the data set <a href="http://www.kaggle.com/sarahvch/predicting-who-pays-back-loans#loan_data.csv">here</a></p><p><strong>Regression<br></strong>For the regression problem, the dataset that will be used is the <a href="https://www.kaggle.com/camnugent/california-housing-prices">California Housing Prices </a>data set. The problem is to determine house prices from the features given in the data set.</p><p><strong>Content <br></strong>The data pertains to the houses found in a given California district and some summary stats about them based on the 1990 census data.<br><strong>Columns<br>-</strong>longitude<br>-latitude<br>-housing_median_age<br>-total_rooms<br>-total_bedrooms<br>-population<br>-households<br>-median_income<br>-median_house_value: This is our target variable<br>-ocean_proximity.</p><p>This series will entail comparing all the machine learning algorithms I have learnt on the regression and classification datasets and see which of them performs the best.</p><p>The first of the series will be using Logistic Regression to solve the Liver disease classification problem. The first blog post can be accessed <a href="http://medium.com/@oluwabukunmige/logistic-regression-in-scikit-learn-a-step-by-step-process-64946e19d37f">here</a>.</p><p>Thank you and I can’t wait to get started.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=249a3a0729f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pipeline for Exploratory Data Analysis and Data Cleaning.]]></title>
            <link>https://medium.com/@oluwabukunmige/pipeline-for-exploratory-data-analysis-and-data-cleaning-6adce7ac0594?source=rss-667aa5802eed------2</link>
            <guid isPermaLink="false">https://medium.com/p/6adce7ac0594</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <dc:creator><![CDATA[Oluwabukunmi Ige]]></dc:creator>
            <pubDate>Wed, 22 Aug 2018 14:58:58 GMT</pubDate>
            <atom:updated>2018-08-22T14:58:58.052Z</atom:updated>
            <content:encoded><![CDATA[<p>Exploratory data analysis(EDA) according to Wikipedia is an approach to analyzing data-sets to summarize their main characteristics, often with visual methods. EDA in a data science context refers to the critical process of performing initial investigations on data so as to discover patterns,to spot anomalies,to test hypothesis and to check assumptions with the help of summary statistics and graphical representations.</p><p>Data cleaning on the other hand is the process of detecting, correcting and ensuring that your given data set is free from error, consistent and usable by identifying any errors or corruptions in the data, correcting or deleting them, or manually processing them as needed to prevent the error from corrupting our final analysis.</p><p>EDA and data cleaning both go pari passu as we prepare our data for analysis. Their importance cannot be over emphasized when carrying our data science tasks on our data set. Hence the need for this article.</p><p>In this article i am going to relate the various steps that a data scientist should perform on his data and the importance of those steps obtaining a clean data set for analysis. The steps will be highlighted by bullet points and will be a combination of both EDA and data cleaning techniques. I have documented all the code examples i’m going to be using <a href="http://github.com/Oluwabukunmige/Pipeline-for-Exploratory-Data-Analysis-and-Data-Cleaning.">here</a>, so you can understand and follow through.</p><ul><li><strong>Visual inspection of data</strong>: This involves viewing the first 5 and last five rows of data frame to have an idea how the data is presented.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W4Eo39kEDEIut00t5VbH8w.png" /></figure><p>From the image above we already picture some missing data. Next</p><ul><li><strong>Carryout Summary statistics</strong>: This gives us a quick and simple description of the data. It will tell us information such as mean, median, mode, variance. Outliers can also be spotted. It can be performed on columns that contain numeric data.</li><li><strong>Converting to suitable data types:</strong> Data types may come in a wrong format which makes analysis difficult, for instance a column supposed to contain numeric data may be stored as string or a column supposed to contain categorical data stored as a string. Hence it always necessary to convert to suitable data types to improve ease of analysis</li><li><strong>Frequency Count</strong>: This is used to show us the value count of each object or numeric data in each column</li><li><strong>Data visualization</strong> using <strong>Matplotlib:</strong> This package is used to visualize data in python. The package contains statistical tools such as boxplot, histogram,scatter plot e.t.c. Histogram is used for discrete data and to compare the relationship among each numeric data in a column, scatter plot used to show the relationship between 2 numeric variable and box plots is used for basic summary statistics between a numeric and a non-numeric variable.</li><li><strong>Checking for tidy data: </strong>Data frames have to be checked to see if it complies with the tidy data principle. What’s the tidy data principle you may ask?, the tidy data principle states that columns represent separate variables, rows represent individual observations and each type of observational unit forms a table. This is shows a standard way to organize a data values within a data set. For further reading on tidy data, <a href="https://www.jstatsoft.org/article/view/v059i10/v59i10.pdf">Hadley Wickham’s</a> paper on tidy data is worth the read. To solve the problem of untidy data, the pandas function<strong> melt</strong> always comes in handy. The image below will show a before and after process of melting. After melting you can always <strong>parse </strong>out to obtain the desired column variable.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*10zBEpdEBXCww-oBVDEnbQ.png" /><figcaption>Before Melting</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*Oazb5fVUtHJU98WIO5V4wg.png" /><figcaption>After Melting</figcaption></figure><ul><li><strong>Combining suitable data-sets : </strong>Data may not always come in one data file or table for you to load. This is because it is easier to share and store data files this way, other times it may be because there’s a new data file for each day, stock series data is a ready example. Whatever the case may be, it’s always best practice to combine these data sets for analysis. Pandas <strong>concatenate</strong>, <strong>glob</strong> and<strong> join </strong>functions are always very useful for combining data sets. The <strong>glob</strong> function can be used to find file based on a particular pattern and join them into a single data frame. An example is shown below:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*ypoe84U7s3_gbXrgEuH5jQ.png" /></figure><p>From the bloc of code above we can see that we were able to combine 3 data sets. This is the beauty of panda’s glob function. The full code is accessible <a href="http://github.com/Oluwabukunmige/Pipeline-for-Exploratory-Data-Analysis-and-Data-Cleaning.">here</a></p><ul><li><strong>Handling Inconsistent data entries:</strong> Inconsistent data entries are basically similar data entries that are stored in a way that makes them dissimilar due factors such as white spaces, different letter cases, punctuation marks etc. It is always necessary to match and combine all similar data entries.</li><li><strong>String Manipulation: </strong>Most of data cleaning will involve string manipulation because most the world’s data involves unstructured text. String manipulation is an essential way of obtaining numeric data from strings. Python’s built in string manipulation library <strong>Regex </strong>always come in handy during string manipulation. Regex uses pattern matching to match the specified variable and can be used continuously. An example of string manipulation using Regex is shown below</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*4SCOFT8qHLHZhCWPC7B91Q.png" /></figure><ul><li><strong>Duplicate and Missing Data</strong>: Duplicate data and missing data is problematic because it can affect your analysis in undesirable ways. It is always necessary to find out why data is missing or being duplicated, whatever the reason duplicate and missing data can be dropped or filled. Missing data can be filled using summary statistic or binary values i.e ones and zeros. Whatever method you choose it is always best to know why the data is being duplicated or missing.</li><li><strong>Using Assert Statements:</strong>Assert statement is a simple way to verify certain information in our data set. Assert statement helps to detect early early warnings and errors and gives us confidence that our code is running correctly. Assert statements work like this: if you give it a statement that is true it will return nothing, if you give a statement that is false it will return an error. Below is code bloc of an assert statement.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*ic-mZmZUaRvxdG7K3K7Lpw.png" /><figcaption>Assert Statement</figcaption></figure><p><strong>Conclusion</strong></p><p>The Exploratory Data Analysis(EDA) and data cleaning techniques listed in this article are among the various techniques used in preparing your data for analysis. Although, it is important to note that not all of these techniques will work for all data sets, so it always import to study your data holistically to know which of the techniques to employ. You can find the code for each technique stated in this article in this github <a href="http://github.com/Oluwabukunmige/Pipeline-for-Exploratory-Data-Analysis-and-Data-Cleaning.">repository</a>.</p><p>If you have any comments or additions be sure to leave them in the comment section and if you did enjoy the article do not forget to give a round of applause.</p><p>Information graphic types<a href="https://en.wikipedia.org/wiki/Exploratory_data_analysis#">[hide]</a></p><ul><li><a href="https://en.wikipedia.org/wiki/Line_chart">Line chart</a> • <a href="https://en.wikipedia.org/wiki/Bar_chart">Bar chart</a></li><li><a href="https://en.wikipedia.org/wiki/Histogram">Histogram</a> • <a href="https://en.wikipedia.org/wiki/Scatterplot">Scatterplot</a></li><li><a href="https://en.wikipedia.org/wiki/Boxplot">Boxplot</a> • <a href="https://en.wikipedia.org/wiki/Pareto_chart">Pareto chart</a></li><li><a href="https://en.wikipedia.org/wiki/Pie_chart">Pie chart</a> • <a href="https://en.wikipedia.org/wiki/Area_chart">Area chart</a></li><li><a href="https://en.wikipedia.org/wiki/Control_chart">Control chart</a> • <a href="https://en.wikipedia.org/wiki/Run_chart">Run chart</a></li><li><a href="https://en.wikipedia.org/wiki/Stem-and-leaf_display">Stem-and-leaf display</a> • <a href="https://en.wikipedia.org/wiki/Cartogram">Cartogram</a></li><li><a href="https://en.wikipedia.org/wiki/Small_multiple">Small multiple</a> • <a href="https://en.wikipedia.org/wiki/Sparkline">Sparkline</a></li><li><a href="https://en.wikipedia.org/wiki/Table_(information)">Table</a></li></ul><p>Related topics<a href="https://en.wikipedia.org/wiki/Exploratory_data_analysis#">[hide]</a></p><ul><li><a href="https://en.wikipedia.org/wiki/Data">Data</a> • <a href="https://en.wikipedia.org/wiki/Information">Information</a></li><li><a href="https://en.wikipedia.org/wiki/Big_data">Big data</a> • <a href="https://en.wikipedia.org/wiki/Database">Database</a></li><li><a href="https://en.wikipedia.org/wiki/Chartjunk">Chartjunk</a> • <a href="https://en.wikipedia.org/wiki/Visual_perception">Visual perception</a></li><li><a href="https://en.wikipedia.org/wiki/Regression_analysis">Regression analysis</a> • <a href="https://en.wikipedia.org/wiki/Statistical_model">Statistical model</a></li><li><a href="https://en.wikipedia.org/wiki/Misleading_graph">Misleading graph</a></li><li><a href="https://en.wikipedia.org/wiki/Template:Data_Visualization">v</a></li><li><a href="https://en.wikipedia.org/w/index.php?title=Template_talk:Data_Visualization&amp;action=edit&amp;redlink=1">t</a></li><li><a href="https://en.wikipedia.org/w/index.php?title=Template:Data_Visualization&amp;action=edit">e</a></li></ul><p>In <a href="https://en.wikipedia.org/wiki/Statistics">statistics</a>, <strong>exploratory data analysis</strong> (<strong>EDA</strong>) is an approach to <a href="https://en.wikipedia.org/wiki/Data_analysis">analyzing</a> <a href="https://en.wikipedia.org/wiki/Data_set">data sets</a> to summarize their main characteristics, often with visual methods.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6adce7ac0594" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>