<?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 Nick Cox on Medium]]></title>
        <description><![CDATA[Stories by Nick Cox on Medium]]></description>
        <link>https://medium.com/@nickdcox?source=rss-9addc0db62fa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*iyAP22Kbk0cKurxMLlPx-A.jpeg</url>
            <title>Stories by Nick Cox on Medium</title>
            <link>https://medium.com/@nickdcox?source=rss-9addc0db62fa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:37:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nickdcox/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[The Best Data is Free Data, Of Course]]></title>
            <link>https://medium.com/data-science/the-best-data-is-free-data-of-course-b88230b5b47f?source=rss-9addc0db62fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/b88230b5b47f</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[open-data]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Nick Cox]]></dc:creator>
            <pubDate>Mon, 10 Jan 2022 13:29:37 GMT</pubDate>
            <atom:updated>2022-01-10T13:29:37.949Z</atom:updated>
            <content:encoded><![CDATA[<h4>Access a bounty of open data with the Socrata Open Data API and sodapy package</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*skqocmcrlc_2T3BM" /><figcaption>Photo by <a href="https://unsplash.com/@janicetea?utm_source=medium&amp;utm_medium=referral">j</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>Commonly used data repositories for data science projects are Kaggle and the UCI Machine Learning Repository. However, many of the datasets available there are synthetic and not representative of the real world.</p><p>There is a bounty of real-world open data available from federal, state and local governments that you can and should be using for your projects. In this article, I will share the easy steps you should follow to gain access. All you need is the Socrata Open Data API and the sodapy package.</p><p>For explanatory purposes, we will be using the <a href="https://data.sfgov.org/Transportation/Air-Traffic-Passenger-Statistics/rkru-6vcg">Air Traffic Passenger Statistics</a> dataset from DataSF, the San Francisco open data repository.</p><h4>1. Obtain Socrata App Token</h4><p>Your first step is to sign up for a free account at <a href="https://data.sfgov.org/login">https://data.sfgov.org/login</a> to obtain an app token. Once you have your credentials, click Create New App Token and complete the required fields.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n3urNJv9bESOfLGDsI3aDg.png" /></figure><p>You will be asked to input a name and a description for the app token, any unique name will do. Your app token is automatically generated and displayed on screen.</p><p>The process for obtaining an app token for other open data repositories is the same. For example, NYC OpenData can be found at the following address: <a href="https://data.cityofnewyork.us/login">https://data.cityofnewyork.us/login</a></p><h4>2. Install sodapy</h4><p>The next step is to install the sodapy package with pip install sodapy</p><h4>3. Establish a Connection</h4><p>We will now jump into our Python IDE to establish a connection with the Socrata Open Data API. I have used Jupyter Lab:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27ac2c4ee2d59d5f842bd21f1278429f/href">https://medium.com/media/27ac2c4ee2d59d5f842bd21f1278429f/href</a></iframe><p>The first step is to import the sodapy package. Next, we must define our data source and provide our app token:</p><ul><li><strong>DATA_LINK: </strong>this will differ depending on which open data repository you are trying to access and can be obtained from the URL. For dataSF it is data.sfgov.org, while for New York Open Data it is data.cityofnewyork.us.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9pra4JscJUqrh82ovdluDA.png" /></figure><ul><li><strong>DATA_ID: </strong>this is the API endpoint, a designator specific to the dataset you are trying to access and can also be obtained from the URL:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tdqnkn21BjWfqYB4q3ieSA.png" /></figure><ul><li><strong>APP_TOKEN:</strong> this is the token you obtained in an earlier step. In the code above I input ‘redacted’ in order to keep my own app token private.</li></ul><p>Finally, we establish the connection by instantiating a Socrata object and naming it <em>client</em>. We pass the data source and app token.</p><h4>4. Request Data</h4><p>Requesting data with the Socrata Open Data API can be done with just one line of code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b50f1d83ca03d5a772ced8109210fe1/href">https://medium.com/media/5b50f1d83ca03d5a772ced8109210fe1/href</a></iframe><p>We call the get() method on our Socrata object, <em>client</em>. We pass the DATA_ID that we defined earlier. By default the first 1,000 records in the dataset will be requested. We will soon learn how to request more records per API call.</p><p>It is important to note that the Socrata API will <strong>not </strong>return the same records when repeating exactly the same request. To guarantee consistent responses, the <strong>order </strong>parameter should be used with a value of ‘:id’, which sorts the dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/207951574094cf568d58d4ecb5038256/href">https://medium.com/media/207951574094cf568d58d4ecb5038256/href</a></iframe><h4>5. Getting Data into a DataFrame</h4><p>By default, the requested data is returned in JSON format:</p><pre>[{&#39;activity_period&#39;: &#39;200507&#39;,<br>  &#39;operating_airline&#39;: &#39;ATA Airlines&#39;,<br>  &#39;operating_airline_iata_code&#39;: &#39;TZ&#39;,<br>  &#39;published_airline&#39;: &#39;ATA Airlines&#39;,<br>  &#39;published_airline_iata_code&#39;: &#39;TZ&#39;,<br>  &#39;geo_summary&#39;: &#39;Domestic&#39;,<br>  &#39;geo_region&#39;: &#39;US&#39;,<br>  &#39;activity_type_code&#39;: &#39;Deplaned&#39;,<br>  &#39;price_category_code&#39;: &#39;Low Fare&#39;,<br>  &#39;terminal&#39;: &#39;Terminal 1&#39;,<br>  &#39;boarding_area&#39;: &#39;B&#39;,<br>  &#39;passenger_count&#39;: &#39;27271&#39;},<br> {&#39;activity_period&#39;: &#39;200507&#39;,<br>  &#39;operating_airline&#39;: &#39;ATA Airlines&#39;,<br>  &#39;operating_airline_iata_code&#39;: &#39;TZ&#39;,<br>  &#39;published_airline&#39;: &#39;ATA Airlines&#39;,<br>  &#39;published_airline_iata_code&#39;: &#39;TZ&#39;,<br>  &#39;geo_summary&#39;: &#39;Domestic&#39;,<br>  &#39;geo_region&#39;: &#39;US&#39;,<br>  &#39;activity_type_code&#39;: &#39;Enplaned&#39;,<br>  &#39;price_category_code&#39;: &#39;Low Fare&#39;,<br>  &#39;terminal&#39;: &#39;Terminal 1&#39;,<br>  &#39;boarding_area&#39;: &#39;B&#39;,<br>  &#39;passenger_count&#39;: &#39;29131&#39;}]</pre><p>Fortunately it is super easy to get your JSON data in to a pandas DataFrame:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0b858ff77041038f75c49ff325ed5a2/href">https://medium.com/media/a0b858ff77041038f75c49ff325ed5a2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5dIiVUuVGyG9JX3tw889_A.png" /><figcaption>First five records of DataFrame.</figcaption></figure><p>At this point you now have the capability to use sodapy to import open data into a DataFrame ready for analysis. There are however a few advanced topics that we must cover so that you can make the most of the Socrata Open Data API - paging through a dataset and advanced filtering.</p><h4>6. Paging Through a Dataset</h4><p>Open data datasets can be very large, and you may need to page through the dataset in multiple requests. The following code requests the record count of the dataset and calculates how many pages there are for a page size of 1,000 records:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcd385bdbf263299728b8e94df1bc53c/href">https://medium.com/media/bcd385bdbf263299728b8e94df1bc53c/href</a></iframe><pre>:: Number of Records Available: 46,670<br>:: Number of Pages: 47</pre><p>This next code segment pages through the dataset according to the selected page_size and calculated num_pages:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb6506cf4ca841e401e74daabd1d01a5/href">https://medium.com/media/bb6506cf4ca841e401e74daabd1d01a5/href</a></iframe><ul><li><strong>limit: </strong>specifies the number of records to request (optional).</li><li><strong>offset:</strong> specifies where in the dataset we should start our request, in this case at the first available record (optional).</li><li><strong>order=’:id’: </strong>specifies that the dataset should be ordered</li></ul><p>The order of the results of a query are not implicitly ordered, so if you’re paging, make sure you provide an $order <a href="https://dev.socrata.com/docs/queries/">clause</a> or at a minimum use the record ID: $order=:id. That will guarantee that the order of your results will be stable as you page through the dataset.</p><h4>7. Advanced Filtering</h4><p>Instead of requesting the full dataset, it is possible to request a filtered dataset by adding a where clause in the get request. The following code segment requests all records for July 2005:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d254b9316f0e865f401f815389444ca/href">https://medium.com/media/4d254b9316f0e865f401f815389444ca/href</a></iframe><h4>Concluding Remarks</h4><p>From this article you have learned how to access open data datasets using the Socrata Open Data API and the sodapy package. New York and San Francisco are only two of many repositories available for free - I encourage you to explore other open data repositories.</p><p>If you enjoy reading stories like these and want to support me as a writer, consider <a href="https://medium.com/@nickdcox/membership">signing up to become a Medium member</a>. It’s $5 a month, giving you unlimited access to stories on Medium. If you <a href="https://medium.com/@nickdcox/membership">sign up using my link</a>, I’ll earn a small commission.</p><p>Please also check out my series <strong>Learn Python Data Analytics by Example</strong>:</p><ul><li><a href="https://towardsdatascience.com/learn-python-data-analytics-by-example-ny-parking-violations-e1ce1847fa2">Learn Python Data Analytics By Example: NYC Parking Violations</a></li><li><a href="https://towardsdatascience.com/learn-python-data-analytics-by-example-airline-arrival-delays-e26356e8ae6b">Learn Python Data Analytics By Example: Airline Arrival Delays</a>.</li><li><a href="https://towardsdatascience.com/learn-python-data-analytics-by-example-chicago-traffic-crashes-4840f6f15ed">Learn Python Data Analytics by Example: Chicago Traffic Crashes</a></li></ul><p>And my other recently published articles:</p><ul><li><a href="https://towardsdatascience.com/causal-inference-using-bayesian-structural-time-series-models-ab1a3da45cd0">Causal Inference Using Bayesian Structural Time-Series Models</a></li><li><a href="https://towardsdatascience.com/elevate-your-data-science-abilities-learn-resourcefulness-5ae879a6b3b7">Elevate Your Data Science Abilities: Learn Resourcefulness</a></li><li><a href="https://medium.datadriveninvestor.com/did-you-have-coronavirus-and-not-even-know-it-i-know-who-did-77200e76149e">Did You Have Coronavirus and Not Even Know It? I Know Who Did!</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b88230b5b47f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/the-best-data-is-free-data-of-course-b88230b5b47f">The Best Data is Free Data, Of Course</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Fresh Perspective on What Developer Experience Really Should Be]]></title>
            <link>https://levelup.gitconnected.com/a-fresh-perspective-on-what-developer-experience-really-should-be-8c270f81339a?source=rss-9addc0db62fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c270f81339a</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[culture]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Nick Cox]]></dc:creator>
            <pubDate>Tue, 30 Mar 2021 02:49:32 GMT</pubDate>
            <atom:updated>2021-03-30T02:49:32.975Z</atom:updated>
            <content:encoded><![CDATA[<h4>Actionable steps to improve developer experience in your organization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J36Pw8uh6tk1z47e" /><figcaption>Photo by <a href="https://unsplash.com/@heylagostechie?utm_source=medium&amp;utm_medium=referral">heylagostechie</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>Developers are often the powerhouse of our organizations, the lifeblood of the products we offer to our customers and earn our revenue from. Thus, it is super important that we provide them with the best experience possible, so that we can keep them motivated, successful, and happy.</p><p>Practitioners and writers often comment on the equivalence between developer experience (DX) and user experience (UX) when the user of the software is a developer. This is not a bad definition, but it is very narrow in scope. I have chosen to adopt a more fulsome definition for developer experience that encompasses the entirety of the organizational environment and culture that we create for our developers.</p><p>In this article, I offer actionable steps you should take to improve the developer experience in your organization, beyond the UX aspects of the developer platform itself. Here is a summary of what you can expect when you read on:</p><ul><li>Enhance business knowledge and understanding</li><li>Give your developers a voice</li><li>Automate the mundane and repetitive tasks</li><li>Schedule meetings at non-disruptive times</li><li>Equip your developers with the best possible tools</li><li>Deploy documentation-as-code</li><li>Remove roadblocks and obstacles</li><li>Allow time for refactoring</li><li>Acknowledge estimates for what they are</li><li>Invest in the skills of your developers</li></ul><p>I started my career as a consultant and therefore I like to think big picture and holistically when I solve problems. It is because of this that some of my recommendations may not be what you were expecting. But, I promise that if you take a holistic approach too, you will experience measurable improvements as a result.</p><h4>Action: Enhance Business Knowledge and Understanding</h4><p>Ensure that your developers are well versed in the mission and objectives of your organization. There is no better way to achieve buy-in and focus than having a highly engaged workforce. And there is no better way to achieve engagement than to have a workforce who believes in and is passionate about the mission of your organization.</p><p>It is a worthwhile investment for your developers to spend time learning about the products and processes of the organization, the industry it operates within, and the nature of your customer base.</p><p>A developer with broad and deep knowledge of your organization will code with purpose and will deliver better code.</p><h4>Action: Give Your Developers a Voice</h4><p>Empower your developers by including them in the decision-making process, not just as it relates to development activities, but also broader organizational initiatives and decisions.</p><p>This really goes hand-in-hand with the previous action in that your developers will be more highly engaged if they are involved in the decisions that make a difference. Your developers are highly-skilled and knowledgeable and may offer new and different perspectives that could unlock unrealized potential.</p><h4>Action: Automate the Mundane and Repetitive Tasks</h4><p>We do not want our highly-skilled developers wasting their time performing mundane or repetitive tasks. If a developer is spending 30 minutes a day on such tasks, this equates to 10 hours per month and 120 hours per year that a developer could be dedicating to new functionality and improving the customer experience.</p><p>Allow time for your developers to automate these mundane and repetitive tasks. The upfront investment pays dividends for years to come. Automation of testing should also be considered.</p><h4>Action: Schedule Meetings at Non-Disruptive Times</h4><p>Most of us do not enjoy endless time-consuming meetings that do not have a clear purpose nor useful outcomes. Your developers are even more loathsome about meetings than most. And it is not just the duration of the meetings that matter, it is also when they are held.</p><p>Make your meetings purposeful, efficient and schedule them during the least disruptive times for your developers. There is nothing worse than interrupting a developer who is in the middle of coding a winning algorithm.</p><h4>Action: Equip Your Developers with the Best Possible Tools</h4><p>Although I have taken the focus away from UX in this article, having the best tools for your developers is still a must. Functionality, ease of use, availability, collaboration, and good documentation are all important. This applies equally to hardware, software, and cloud services.</p><p>Like an artist or a builder, developers are able to produce their best work when they have the tools they need, but without the frustrations of bad design and poor functionality.</p><p>And as suggested earlier, give your developers a voice in what tools and technology you adopt. An investment in tools and technology is an investment in your developers.</p><h4>Action: Deploy Documentation-as-Code</h4><p>The thrill of coding for developers is creating cool new functionality. Writing documentation in support of it usually does not come with that same thrill. Adopting documentation-as-code, where code and documentation is created and maintained equally, is an alternative approach that your developers may embrace.</p><h4>Action: Remove Roadblocks and Obstacles</h4><p>If you have given your developers a voice and if you are listening, you will learn about the roadblocks and obstacles that they are facing in their day-to-day work. Partner with them to remove the roadblocks and obstacles. Unleash the full power of your developers.</p><p>You should also give your developers the authority to fix problems and remove obstacles without the need to always obtain permission first.</p><h4>Action: Allow Time for Code Refactoring</h4><p>Code refactoring is the process of restructuring existing code without changing its external behavior. It is intended to improve the design and structure while preserving the functionality.</p><p>Allow your developers some time to refactor their existing code. Many developers relish the challenge of improving performance and efficiency. It has the benefits of keeping code fresh and can prevent hours spent to maintain and debug old code. The benefits outweigh the costs.</p><h4>Action: Acknowledge Estimates for What They Are</h4><p>Estimating how many hours and resources are required to develop the requested functionality is an impossible task. Nobody gets it right every single time. By all means, provide your developers with tools and protocols for building estimations, but it is equally important to acknowledge that estimates are just that. Ensure that your developers are continually learning from estimates that were precise and estimate that missed the mark by a wide margin.</p><h4>Action: Invest in the Skills of Your Developers</h4><p>This should be obvious but is often overlooked. Ensure that budget is available to upskill and cross-train your developers. They will enjoy learning new skills and the organization will ultimately benefit from having highly-skilled and leading-edge developers. Training budgets are often the first cut made during trying times. Do not make the same mistake yourself.</p><h4>Concluding Remarks</h4><p>I know that I have given you a lot to consider. You do not have to attempt all of these actions at once. Set a priority list and get started. Your developers will thank you for it.</p><p>Please also check out my series <strong>Learn Python Data Analytics by Example</strong>:</p><ul><li><a href="https://towardsdatascience.com/learn-python-data-analytics-by-example-ny-parking-violations-e1ce1847fa2">Learn Python Data Analytics By Example: NYC Parking Violations</a></li><li><a href="https://towardsdatascience.com/learn-python-data-analytics-by-example-airline-arrival-delays-e26356e8ae6b">Learn Python Data Analytics By Example: Airline Arrival Delays</a>.</li><li><a href="https://towardsdatascience.com/learn-python-data-analytics-by-example-chicago-traffic-crashes-4840f6f15ed">Learn Python Data Analytics by Example: Chicago Traffic Crashes</a></li></ul><p>Any my other recently published articles:</p><ul><li><a href="https://towardsdatascience.com/causal-inference-using-bayesian-structural-time-series-models-ab1a3da45cd0">Causal Inference Using Bayesian Structural Time-Series Models</a></li><li><a href="https://towardsdatascience.com/elevate-your-data-science-abilities-learn-resourcefulness-5ae879a6b3b7">Elevate Your Data Science Abilities: Learn Resourcefulness</a></li><li><a href="https://medium.datadriveninvestor.com/did-you-have-coronavirus-and-not-even-know-it-i-know-who-did-77200e76149e">Did You Have Coronavirus and Not Even Know It? I Know Who Did!</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c270f81339a" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/a-fresh-perspective-on-what-developer-experience-really-should-be-8c270f81339a">A Fresh Perspective on What Developer Experience Really Should Be</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Fresh Take on What Developer Experience (DX) Really Should Be]]></title>
            <link>https://medium.com/geekculture/a-fresh-take-on-what-developer-experience-dx-really-should-be-62501793d563?source=rss-9addc0db62fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/62501793d563</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[culture]]></category>
            <dc:creator><![CDATA[Nick Cox]]></dc:creator>
            <pubDate>Wed, 24 Mar 2021 19:02:48 GMT</pubDate>
            <atom:updated>2021-03-24T19:10:39.701Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Fresh Perspective on What Developer Experience Really Should Be</h3><h4>Actionable steps to improve the developer experience in your organization.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iBNYx2tA9SCmsLJQ" /><figcaption>Photo by <a href="https://unsplash.com/@kobuagency?utm_source=medium&amp;utm_medium=referral">KOBU Agency</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>Developers are often the powerhouse of our organizations, the lifeblood of the products we offer to our customers and earn our revenue from. Thus, it is super important that we provide them with the best experience possible so that we can keep them motivated, successful, and happy.</p><p>Practitioners and writers often comment on the equivalence between developer experience (DX) and user experience (UX) when the user of the software is a developer. This is not a bad definition, but it is very narrow in scope. I have chosen to adopt a more fulsome definition for developer experience that encompasses the entirety of the organizational environment and culture that we create for our developers.</p><p>In this article, I offer actionable steps you should take to improve the developer experience in your organization, beyond the UX aspects of the developer platform itself. Here is a summary of what you can expect when you read on:</p><ul><li>Enhance business knowledge and understanding</li><li>Give your developers a voice</li><li>Automate the mundane and repetitive tasks</li><li>Schedule meetings at non-disruptive times</li><li>Equip your developers with the best possible tools</li><li>Deploy documentation-as-code</li><li>Remove roadblocks and obstacles</li><li>Allow time for refactoring</li><li>Acknowledge estimates for what they are</li><li>Invest in the skills of your developers</li></ul><p>I started my career as a consultant and therefore I like to think big picture and holistically when I solve problems. It is because of this that some of my recommendations may not be what you were expecting. But, I promise that if you take a holistic approach too, you will experience measurable improvements as a result.</p><h4><strong>Action: Enhance Business Knowledge and Understanding</strong></h4><p>Ensure that your developers are well versed in the mission and objectives of your organization. There is no better way to achieve buy-in and focus than having a highly engaged workforce. And there is no better way to achieve engagement than to have a workforce who believes in and is passionate about the mission of your organization.</p><p>It is a worthwhile investment for your developers to spend time learning about the products and processes of the organization, the industry it operates within, and the nature of your customer base.</p><p>A developer with broad and deep knowledge of your organization will code with purpose and will deliver better code.</p><h4><strong>Action: Give Your Developers a Voice</strong></h4><p>Empower your developers by including them in the decision-making process, not just as it relates to development activities, but also broader organizational initiatives and decisions.</p><p>This really goes hand-in-hand with the previous action in that your developers will be more highly engaged if they are involved in the decisions that make a difference. Your developers are highly-skilled and knowledgeable and may offer new and different perspectives that could unlock unrealized potential.</p><h4><strong>Action: Automate the Mundane and Repetitive Tasks</strong></h4><p>We do not want our highly-skilled developers wasting their time performing mundane or repetitive tasks. If a developer is spending 30 minutes a day on such tasks, this equates to 10 hours per month and 120 hours per year that a developer could be dedicating to new functionality and improving the customer experience.</p><p>Allow time for your developers to automate these mundane and repetitive tasks. The upfront investment pays dividends for years to come. Automation of testing should also be considered.</p><h4>Action: Schedule Meetings at Non-Disruptive Times</h4><p>Most of us do not enjoy endless time-consuming meetings that do not have a clear purpose nor useful outcomes. Your developers are even more loathsome about meetings than most. And it is not just the duration of the meetings that matter, it is also when they are held.</p><p>Make your meetings purposeful, efficient and schedule them during the least disruptive times for your developers. There is nothing worse than interrupting a developer who is in the middle of coding a winning algorithm.</p><h4>Action: Equip Your Developers with the Best Possible Tools</h4><p>Although I have taken the focus away from UX in this article, having the best tools for your developers is still a must. Functionality, ease of use, availability, collaboration, and good documentation are all important. This applies equally to hardware, software, and cloud services.</p><p>Like an artist or a builder, developers are able to produce their best work when they have the tools they need, but without the frustrations of bad design and poor functionality.</p><p>And as suggested earlier, give your developers a voice in what tools and technology you adopt. An investment in tools and technology is an investment in your developers.</p><h4>Action: Deploy Documentation-as-Code</h4><p>The thrill of coding for developers is creating cool new functionality. Writing documentation in support of it usually does not come with that same thrill. Adopting documentation-as-code, where code and documentation is created and maintained equally, is an alternative approach that your developers may embrace.</p><h4>Action: Remove Roadblocks and Obstacles</h4><p>If you have given your developers a voice and if you are listening, you will learn about the roadblocks and obstacles that they are facing in their day-to-day work. Partner with them to remove the roadblocks and obstacles. Unleash the full power of your developers.</p><p>You should also give your developers the authority to fix problems and remove obstacles without the need to always obtain permission first.</p><h4>Action: Allow Time for Code Refactoring</h4><p>Code refactoring is the process of restructuring existing code without changing its external behavior. It is intended to improve the design and structure while preserving the functionality.</p><p>Allow your developers some time to refactor their existing code. Many developers relish the challenge of improving performance and efficiency. It has the benefits of keeping code fresh and can prevent hours spent to maintain and debug old code. The benefits outweigh the costs.</p><h4>Action: Acknowledge Estimates for What They Are</h4><p>Estimating how many hours and resources are required to develop the requested functionality is an impossible task. Nobody gets it right every single time. By all means, provide your developers with tools and protocols for building estimations, but it is equally important to acknowledge that estimates are just that. Ensure that your developers are continually learning from estimates that were precise and estimate that missed the mark by a wide margin.</p><h4>Action: Invest in the Skills of Your Developers</h4><p>This should be obvious but is often overlooked. Ensure that budget is available to upskill and cross-train your developers. They will enjoy learning new skills and the organization will ultimately benefit from having highly-skilled and leading-edge developers. Training budgets are often the first cut made during trying times. Do not make the same mistake yourself.</p><h4>Concluding Remarks</h4><p>I know that I have given you a lot to consider. You do not have to attempt all of these actions at once. Set a priority list and get started. Your developers will thank you for it.</p><p>Please also check out my series <strong>Learn Python Data Analytics by Example</strong>:</p><ul><li><a href="https://towardsdatascience.com/learn-python-data-analytics-by-example-ny-parking-violations-e1ce1847fa2">Learn Python Data Analytics By Example: NYC Parking Violations</a></li><li><a href="https://towardsdatascience.com/learn-python-data-analytics-by-example-airline-arrival-delays-e26356e8ae6b">Learn Python Data Analytics By Example: Airline Arrival Delays</a>.</li><li><a href="https://towardsdatascience.com/learn-python-data-analytics-by-example-chicago-traffic-crashes-4840f6f15ed">Learn Python Data Analytics by Example: Chicago Traffic Crashes</a></li></ul><p>Any my other recently published articles:</p><ul><li><a href="https://towardsdatascience.com/causal-inference-using-bayesian-structural-time-series-models-ab1a3da45cd0">Causal Inference Using Bayesian Structural Time-Series Models</a></li><li><a href="https://towardsdatascience.com/elevate-your-data-science-abilities-learn-resourcefulness-5ae879a6b3b7">Elevate Your Data Science Abilities: Learn Resourcefulness</a></li><li><a href="https://medium.datadriveninvestor.com/did-you-have-coronavirus-and-not-even-know-it-i-know-who-did-77200e76149e">Did You Have Coronavirus and Not Even Know It? I Know Who Did!</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62501793d563" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/a-fresh-take-on-what-developer-experience-dx-really-should-be-62501793d563">A Fresh Take on What Developer Experience (DX) Really Should Be</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Causal inference using Bayesian structural time-series models]]></title>
            <link>https://medium.com/data-science/causal-inference-using-bayesian-structural-time-series-models-ab1a3da45cd0?source=rss-9addc0db62fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab1a3da45cd0</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Nick Cox]]></dc:creator>
            <pubDate>Thu, 18 Mar 2021 14:49:22 GMT</pubDate>
            <atom:updated>2021-03-20T15:08:58.578Z</atom:updated>
            <content:encoded><![CDATA[<h3>Causal Inference Using Bayesian Structural Time-Series Models</h3><h4>Investigating the effect of training activities on the volume of bugs reported by a software engineering team</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JViIwBi7kgSjyhgG" /><figcaption>Photo by <a href="https://unsplash.com/@erik_karits?utm_source=medium&amp;utm_medium=referral">Erik Karits</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article I will provide you with a brief introduction to causal inference and why we would need it as a Data Scientist, and then I present a practical example of how to apply the concept using the Python library <a href="https://github.com/dafiti/causalimpact">Causal Impact</a>.</p><h3>Introduction to Causal Inference</h3><p>Britannica defines causal inference with a useful example that we can all understand:</p><blockquote>In a causal inference, one reasons to the conclusion that something is, or is likely to be, the cause of something else. For example, from the fact that one hears the sound of piano music, one may infer that someone is (or was) playing a piano. But although this conclusion may be likely, it is not certain, since the sounds could have been produced by an electronic synthesizer.</blockquote><p>Causal inference is about determining the effect of an event or intervention on a desired outcome metric. It can also be thought of as determining whether a change in the outcome metric was caused by an event or intervention.</p><p>For example, 1) what was the effect of a marketing campaign (the intervention) on the sales of our products (the outcome), and 2) did the sales of our products increase because of a marketing campaign or was it because of a different reason? We can use causal inference to answer these questions.</p><p>Causal inference is commonly utilized when making decisions that can impact millions of people or involve millions of dollars, such as in healthcare, public policy, science and in business. In such cases, it is important for our analysis to be grounded in reliable statistics and not just casual glances at data and plots.</p><p>The challenge with analyzing the effects of an intervention is that we are not then easily able to examine how the series would have trended without that intervention. In our marketing example, we have a record of our sales after the intervention of a campaign, but we do not know what the sales would have been without that intervention.</p><p>This is where causal inference using Bayesian structural time-series models can help us. We can use such a model to predict what would have happened without the intervention, which is called the <em>counterfactual</em>. We can then compare the counterfactual with what we actually observed.</p><h3>Causal Impact Library</h3><p>In 2014, Google released an <a href="http://google.github.io/CausalImpact/">R package</a> for causal inference in time series. The Python <a href="https://github.com/dafiti/causalimpact">Causal Impact</a> library, which we use in our example below, is a full implementation of Google’s model with all functionalities fully ported.</p><p>The implementation of the library is best explained by its author:</p><blockquote>The main goal of the algorithm is to infer the expected effect a given intervention (or any action) had on some response variable by analyzing differences between expected and observed time series data.</blockquote><blockquote>Data is divided in two parts: the first one is what is known as the “pre-intervention” period and the concept of <a href="https://en.wikipedia.org/wiki/Bayesian_structural_time_series">Bayesian Structural Time Series</a> is used to fit a model that best explains what has been observed. The fitted model is used in the second part of data (“post-intervention” period) to forecast what the response would look like had the intervention not taken place. The inferences are based on the differences between observed response to the predicted one which yields the absolute and relative expected effect the intervention caused on data.</blockquote><h3>Causal Inference by Example</h3><p>Here is the scenario we will work with:</p><ul><li>A streaming service, WebFlix, delivers its content through several channels: iOS app, Android app, Roku app, Fire TV app and web browsers.</li><li>Each channel is managed by a different software engineering team.</li><li>The engineering teams track the number of bugs reported each week and monitor patterns.</li><li>Management of the Web team identified a worrying upwards trend in the number of bugs reported in early 2020 and provided training to <em>only </em>that team in May 2020 to address the problem.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*3gk9HENLA8B8-iHnksrUPw.png" /></figure><p>Following the training, the number of bugs reported for the Web team decreased and stabilized for the remainder of 2020.<strong> Was this decrease in bugs reported a result of the training provided or was there something else?</strong></p><p>Our dataset contains weekly bug reporting for each of the software engineering teams. All code and data is available in this <a href="https://github.com/nickdcox/ml-causal-inference-swe">GitHub repo</a>.</p><p>You can see in the below line plot the increase in bugs reported for the Web team in the first part of 2020. The red dashed line indicates the week in which training was provided.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ASDJ7MPNgu1cwyk22vWEdw.png" /></figure><p>This next line plot shows the trends of bugs reported by all of the software engineering teams. Bug reporting for all of the teams other than Web is fairly stable throughout the year, bouncing around within a consistent band.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2QRgxO5NTx9jf40Q6cRELg.png" /></figure><p>Based on the above line plots, we could make a preliminary conclusion that the training provided is a possible cause for the reduction in bugs reported for the Web team. However, to increase confidence in our conclusion we will utilize the Causal Impact<em> </em>library for our statistical analysis.</p><p>Before we are able to used Causal Impact,<em> </em>we need to transform our DataFrame into a wide format, so that each software engineering team has a column listing the number of bugs reported per week. We can use the Pandas pivot table function to do this. We also need to ensure that our date variable is set to the index and that the Web variable is moved to the first column of the DataFrame.</p><p>The model will use the bug reporting data for all of the software engineering teams to help us determine whether the specified intervention was the true cause of the decrease in bugs reported for the Web team.</p><p>Here is the code and the resulting DataFrame:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/921de8b51ce9a25cdb5c2e627173439b/href">https://medium.com/media/921de8b51ce9a25cdb5c2e627173439b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*zQbzansMvklghGYSv0vdOg.png" /></figure><p>Using and interpreting the results of the Causal Impact library is incredibly easy. We start by defining the period of time before the intervention (training was provided during the last week of May 2020) and the period after the intervention.</p><p>We then run the model by providing the wide DataFrame and the two periods we just defined. Once processing is complete, we can plot the results using the three available plot types: original, pointwise and cumulative:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71994e4061c3c9c4c06684d07e09e95e/href">https://medium.com/media/71994e4061c3c9c4c06684d07e09e95e/href</a></iframe><p>The first plot below shows the actual bugs reported for the Web software engineering team (y) versus the prediction for the same team (predicted), taking into consideration both the bugs reported in January to May 2020 for the Web team and the bugs reported throughout the year by the other software engineering teams.</p><p>It is evident from the plot, that the prediction for the Web team from June to December 2020 is above the actual reporting. This indicates that an intervention took place in May 2020 that positively impacted the number of bugs reported by the Web team from June onwards. This further supports a conclusion that the training provided to the Web team in May 2020 was the cause for the reduction in bugs reported from June onwards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A0-VHiUx6uAQw8tL-wTnkg.png" /></figure><p>The next plot shows the difference between the actual series and the predicted series, referred to as the point effects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*87c7XzG7UVEOHUlTm-v0sw.png" /></figure><p>This final plot shows the cumulative effect, which is basically the summation of the point effects accumulated over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uubAx4KT-mo1dBx28y0Agg.png" /></figure><p>The Causal Impact<em> </em>library can also provide us with numerical and statistical outputs for further analysis:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e275bda956be8fc533472ac136ed4e2/href">https://medium.com/media/9e275bda956be8fc533472ac136ed4e2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M10lU3hSufFvltxpjKHNxw.png" /></figure><p>And finally, we can also produce a written report explaining the results of our analysis with just one line of code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a26d7cbbef716ce598896636674a04e7/href">https://medium.com/media/a26d7cbbef716ce598896636674a04e7/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OKlTWTPScVN1vCU7SWX3iw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hR14_wGebdwc-9hkg-XwUg.png" /></figure><p><strong>This report confirms our earlier preliminary conclusions that the cause of the reduction in bugs reported for the Web software engineering team from June 2020 onwards was the training provided to the team in May 2020. The probability of obtaining this effect by chance is very small and therefore the causal effect can be considered statistically significant.</strong></p><p><strong>The intervention, which is the training provided, had an effect of -21.03 bugs reported, with a 95% interval. Providing the training was a good decision because it had the desired effect.</strong></p><h3>Concluding Remarks</h3><p>Causal inference is a difficult problem to solve, but one that data scientists are increasingly being asked to address. The introduction of libraries such as Causal Impact give us a good tool to be able to make headway on this.</p><p>As you saw in the bug reporting example, the library is super easy to use and the results can be quickly interpreted and understood. We can quickly gain confidence in any conclusions drawn and communicate our results to stakeholders.</p><p>Please also check out my series <strong>Learn Python Data Analytics by Example</strong>:</p><ul><li><a href="https://towardsdatascience.com/learn-python-data-analytics-by-example-ny-parking-violations-e1ce1847fa2">Learn Python Data Analytics By Example: NYC Parking Violations</a></li><li><a href="https://towardsdatascience.com/learn-python-data-analytics-by-example-airline-arrival-delays-e26356e8ae6b">Learn Python Data Analytics By Example: Airline Arrival Delays</a>.</li><li><a href="https://towardsdatascience.com/learn-python-data-analytics-by-example-chicago-traffic-crashes-4840f6f15ed">Learn Python Data Analytics by Example: Chicago Traffic Crashes</a></li></ul><p>Any my other recently published articles:</p><ul><li><a href="https://towardsdatascience.com/elevate-your-data-science-abilities-learn-resourcefulness-5ae879a6b3b7">Elevate Your Data Science Abilities: Learn Resourcefulness</a></li><li><a href="https://medium.datadriveninvestor.com/did-you-have-coronavirus-and-not-even-know-it-i-know-who-did-77200e76149e">Did You Have Coronavirus and Not Even Know It? I Know Who Did!</a></li></ul><ul><li><a href="https://github.com/dafiti/causalimpact">dafiti/causalimpact</a></li><li><a href="https://github.com/nickdcox/ml-causal-inference-swe">nickdcox/ml-causal-inference-swe</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab1a3da45cd0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/causal-inference-using-bayesian-structural-time-series-models-ab1a3da45cd0">Causal inference using Bayesian structural time-series models</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elevate Your Data Science Abilities: Learn Resourcefulness]]></title>
            <link>https://medium.com/data-science/elevate-your-data-science-abilities-learn-resourcefulness-5ae879a6b3b7?source=rss-9addc0db62fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ae879a6b3b7</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[skills]]></category>
            <category><![CDATA[learning]]></category>
            <dc:creator><![CDATA[Nick Cox]]></dc:creator>
            <pubDate>Thu, 11 Feb 2021 17:23:38 GMT</pubDate>
            <atom:updated>2021-02-11T17:23:38.498Z</atom:updated>
            <content:encoded><![CDATA[<h4>Join me in this new series where we explore the soft-skills that will elevate your effectiveness as a data scientist</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JsFHgLmDALPEKOW7" /><figcaption>Photo by <a href="https://unsplash.com/@noe_kf?utm_source=medium&amp;utm_medium=referral">noe fornells</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is Resourcefulness?</h3><p>The coconut octopus is perhaps one of the most resourceful animals in the world. Octopi are commonly known for their intelligence, but the coconut octopus stands out from the rest due to one amazing trait: they often carry coconuts and seashells to be used as armored protection.</p><p>Because they are usually 3 to 6 inches in length and non-poisonous, protection is a must to avoid being lunch for another marine animal. But that is not all. These resourceful undersea creatures are capable of bipedal locomotion, better known as walking. Talk about amazing!</p><p>To be resourceful is to <strong>have the ability to find quick and clever ways to overcome difficulties</strong>. It is to be a problem solver with the resources you have at hand. And in data science we have no shortage of problems that we need to solve in completing our work.</p><p>I grew up in New Zealand and we have an expression that we can build or fix anything using number 8 fencing wire. We also refer to this as kiwi ingenuity, which is a can-do attitude and ability to think laterally to solve a problem.</p><p>In New Zealand we take pride in being a resourceful people, but I was not born with this skill. I had to learn it. It is a skill that requires deliberate practice and attention to develop it. But when you do, it is a skill that will bring countless benefits to you and your employer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JkC48MAp7btA3_iF" /><figcaption>Photo by <a href="https://unsplash.com/@farbensammler?utm_source=medium&amp;utm_medium=referral">Peter Aschoff</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What Are the Benefits of Being Resourceful?</h3><ul><li><strong>Resourceful people are open-minded: </strong>they are open to new ideas, opinions and challenges. Resourceful people are avid readers and explorers and are always learning.</li><li><strong>Resourceful people are self-assured: </strong>they are equally confident in what they know and in what they do not know. Resourceful people dare to ask for what they need.</li><li><strong>Resourceful people are creative:</strong> this is where the concepts of number 8 wire and ingenuity come in to play the most. Resourceful people are open to new and different solutions. They do not believe that a problem must be solved one way because it always has been.</li><li><strong>Resourceful people are proactive: </strong>they will not sit on their hands and wait for a solution to arrive. Resourceful people will stand up and take the lead, gathering like-minded colleagues to join them for the journey.</li><li><strong>Resourceful people are persistent: </strong>they know that there are many ways to solve a problem and that sometimes the problem will not be solved on the first attempt. But, they will keep on trying until it is done.</li><li><strong>Resourceful people are problem solvers: </strong>when faced with a new problem, resourceful people have the skills to both apply past learnings and to seek out new knowledge to find the best solutions.</li><li><strong>Resourceful people are adaptable: </strong>they are not bound to a single approach to all problems and will gladly seek out the advice of colleagues to find alternative ways. In fact, they feel accomplished when they do.</li></ul><h3>How Do I Become Resourceful?</h3><p>At the heart of it, being resourceful is about physical action. Here are some tangible ways for you to develop and demonstrate your resourcefulness:</p><ul><li><strong>Hone your research skills: </strong>In my mind, being resourceful is about knowing how and where to find the information that you need. Create a directory of useful resources that you can research when the need arises. As data scientists there are many resources at our disposal, often at no cost: Google Search, Git Hub, Medium, Stack Overflow and many more. Oftentimes you do not need to reinvent the wheel, as the solution or at least tidbits that will help get you there are already available.</li><li><strong>Leverage your network:</strong> It cannot be overstated how important it is to have a strong network to reach out to. Do not be afraid to reach out to former colleagues, business partners and industry experts to ask for help. In addition to obtaining information to help you solve your current problem, you may also learn new skills to add to your toolkit for working on future problems.</li><li><strong>Continually develop new skills:</strong> There is no better way to be resourceful than to add to the resources available to you. In data science there are always new tools, techniques and methods to learn. Keep up to date.</li><li><strong>Know your strengths and weaknesses:</strong> The better that you understand these, the quicker you can determine whether you already have the resources and knowledge needed to solve the problem or whether you need to dive into research or reach out to your network.</li><li><strong>Give yourself time to think and strategize:</strong> A pause to determine your strategy for solving a problem, what resources are required and where you can obtain them will pay endless dividends.</li><li><strong>Be better at leveraging what you already have:</strong> A key to resourcefulness is understanding what resources you already have at your fingertips and how best to use them. It is oftentimes quicker and easier to use what you already have than to seek the resources elsewhere. But, also key is to quickly identify when you do not have what you need.</li></ul><p>In addition to being a skill, resourcefulness is a mind-set, an attitude. Being resourceful requires a conscious effort to take action.</p><h3>Concluding Remarks</h3><p>To achieve what you want, you should not have to rely on the resources that you have or have not got. Your ability to become a resourceful person depends on how you use what you already have and how you obtain what you do not have but need.</p><p>As Tony Robbins once said, it is not the lack of resources, it is your lack of resourcefulness that stops you.</p><p>I have no doubt that my resourcefulness has led to successes in my career and in life. In fact, I enjoy the challenge of solving problems and I enjoy searching for solutions.</p><p>If you too become a resourceful person, you will influence others around you with better thinking and more creativity.</p><p>Please also check out my series <strong>Learn Python Data Analytics by Example</strong>:</p><ul><li><a href="https://towardsdatascience.com/learn-python-data-analytics-by-example-ny-parking-violations-e1ce1847fa2">Learn Python Data Analytics By Example: NYC Parking Violations</a></li><li><a href="https://towardsdatascience.com/learn-python-data-analytics-by-example-airline-arrival-delays-e26356e8ae6b">Learn Python Data Analytics By Example: Airline Arrival Delays</a>.</li><li><a href="https://towardsdatascience.com/learn-python-data-analytics-by-example-chicago-traffic-crashes-4840f6f15ed">Learn Python Data Analytics by Example: Chicago Traffic Crashes</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ae879a6b3b7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/elevate-your-data-science-abilities-learn-resourcefulness-5ae879a6b3b7">Elevate Your Data Science Abilities: Learn Resourcefulness</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn Python Data Analytics by Example — Chicago Traffic Crashes]]></title>
            <link>https://medium.com/data-science/learn-python-data-analytics-by-example-chicago-traffic-crashes-4840f6f15ed?source=rss-9addc0db62fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/4840f6f15ed</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Nick Cox]]></dc:creator>
            <pubDate>Tue, 09 Feb 2021 13:30:14 GMT</pubDate>
            <atom:updated>2021-02-17T12:32:17.821Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learn Python Data Analytics by Example — Chicago Traffic Crashes</h3><h4>A fun project and detailed walkthrough of data analytics steps to help you learn Python, pandas, matplotlib, seaborn and Folium</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w4AZk1uQZoK-tWfepHw3sg.png" /></figure><h3>Introduction</h3><p>While working towards my Master’s in Business Analytics, I found that learning by example is the best way for me to learn Python data analytics. Being given a dataset and a set of coding tasks is much more beneficial than reading a textbook or listening to a professor.</p><p>I want to share this method of learning with others who will also benefit. All you need is a Python development environment (I recommend <a href="https://jupyter.org/">Jupyter Notebook</a>) and a willingness to learn and have fun.</p><p>Included in this article is a list of data analytics tasks, followed by a detailed walkthrough of how to complete the tasks. Please try to complete the tasks yourself before reading through the walkthrough — you will get more out of it that way. Do keep in mind that there are many many ways to solve coding problems, so your code likely will not match mine word for word and that is okay.</p><p>Please also check out: <a href="https://towardsdatascience.com/learn-python-data-analytics-by-example-ny-parking-violations-e1ce1847fa2">Learn Python Data Analytics By Example: NYC Parking Violations</a> and <a href="https://towardsdatascience.com/learn-python-data-analytics-by-example-airline-arrival-delays-e26356e8ae6b">Learn Python Data Analytics By Example: Airline Arrival Delays</a>.</p><h3>Project Description</h3><p>For this project we will use a dataset with a combined nearly 1.5 million records, which represent traffic crashes reported in Chicago from 2013 to 2021 and the vehicles involved in them. The dataset was created in February 2021 and contains data sourced from the <a href="https://data.cityofchicago.org/Transportation/Traffic-Crashes-Vehicles/68nd-jvt3">City of Chicago</a>.</p><p>You will need to install the <a href="https://pandas.pydata.org/">pandas</a>, <a href="https://matplotlib.org/">matplotlib</a>, <a href="https://seaborn.pydata.org/index.html">seaborn</a> and <a href="https://python-visualization.github.io/folium/">Folium</a> libraries, if you do not already have them.</p><h3>Data Analytics Tasks</h3><p>Please perform the following tasks in Python using the <em>crashes.csv</em> and <em>crashes_vehicles.csv</em> datasets available from this <a href="https://1drv.ms/u/s!AoQYKisAOe1libRT6GTcLP6n_B75hA?e=yTTaEr">drive</a>. Also refer to this <a href="https://github.com/nickdcox/learn-traffic-crashes">GitHub repo</a>.</p><ol><li>Read the CSV files containing the Chicago traffic crash data. Identify the column common to both files and merge them together on that column. Then display the total number of reported crashes.</li><li>Change the ‘CRASH_DATE’ column to a date format. Drop observations that did not occur in 2018, 2019 or 2020 (other years have incomplete data).</li><li>Display a plot showing the number of crashes that occur for each hour of the day.</li><li>Name the make of vehicle that was involved in the most daylight crashes in August 2018. Remember that a crash can involve multiple vehicles.</li><li>Determine which weather condition was most prevalent for each type of crash.</li><li>Plot the primary contributing cause of reported crashes, from highest to lowest.</li><li>Display the 10 state license plates involved in the most crashes. Remember that a crash can involve multiple vehicles.</li><li>Display the proportion of crashes in each month of 2019 where alcohol was determined to be the primary contributing cause.</li><li>Determine whether snowmobiles or recreational off-highway vehicles were involved in more crashes.</li><li>Display a cluster map showing the locations of crashes involving a hit and run.</li></ol><h3>Data Dictionary</h3><p><strong>crashes.csv:</strong> Each row in the dataset represents a traffic crash reported in Chicago.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gI7A6U3YYFS0yo6d8AOr-w.png" /></figure><p><strong>crashes_vehicles.csv:</strong> Each row in the dataset represents a vehicle involved in a crash reported in Chicago.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4GIbsDO256QIZjbKyvJkEg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ECkvVPno1TzaZTZD" /><figcaption>Photo by <a href="https://unsplash.com/@ante_kante?utm_source=medium&amp;utm_medium=referral">Ante Hamersmit</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Step 1: Read the CSV files containing the Chicago traffic crash data. Identify the column common to both files and merge them together on that column. Then display the total number of reported crashes. We will need to use the merged DataFrame and the crashes DataFrame throughout this project.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6395ece9dd9ae92e02bf11a801084290/href">https://medium.com/media/6395ece9dd9ae92e02bf11a801084290/href</a></iframe><pre>Total Number of Reported Crashes: 474262</pre><h4>Code Explanation:</h4><p>We start by making the contents of the pandas module available to our program. pandas is an easy to use open source data analysis and manipulation tool, built on top of the Python programming language. We will use it extensively throughout this project.</p><pre>import pandas as pd</pre><p>We import the contents of the <em>crashes.csv</em> file by calling the read_csv() method and store it in a DataFrame, named <em>df_crashes</em>. A DataFrame is a two-dimensional data structure with labeled axes, consisting of data, rows and columns. Think of it like a table built in Microsoft Excel or Microsoft Access. We then repeat the same action for the <em>crashes_vehicles.csv</em> file, naming it <em>df_vehicles</em>. For the <em>crashes_vehicles.csv</em> file, we drop the ‘CRASH_DATE’ column as it is also included in the other file.</p><pre>df_crashes = pd.read_csv(&#39;crashes.csv&#39;, low_memory=False)<br>df_vehicles = pd.read_csv(&#39;crashes_vehicles.csv&#39;, low_memory=False).drop(&#39;CRASH_DATE&#39;, axis=1)</pre><p>To combine the two DataFrames into a single DataFrame, we call the merge() method of pandas. We pass three parameters: the first two are the names of the two DataFrames that we are merging and the third specifies the column common to both. Finally, with a call to the reset_index() function we reset the DataFrame index.</p><pre>df = pd.merge(df_crashes, df_vehicles, on=&#39;CRASH_RECORD_ID&#39;).reset_index()</pre><p>We use the print() function to print the string ‘Total Number of Reported Crashes:’ followed by the number of crashes in the DataFrame. The parameter that we pass to the print() function is made up of two parts. The first is the string ‘Total Number of Reported Crashes:’ surrounded in single quotes, denoting it as a string. The second part of the parameter is calculating the number of crashes in <em>df</em>. We use the nunique() method to calculate the number of unique CRASH_RECORD_ID in <em>df</em>, since a value can repeat.</p><pre>print(&#39;Total Number of Reported Crashes:&#39;, df[&#39;CRASH_RECORD_ID&#39;].nunique())</pre><h3>Step 2: Change the ‘CRASH_DATE’ column to a date format. Drop observations that did not occur in 2018, 2019 or 2020 (other years have incomplete data). Do this for both the merged and the crash DataFrames.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba7b691ead45f9353c8125a528849a49/href">https://medium.com/media/ba7b691ead45f9353c8125a528849a49/href</a></iframe><h4>Code Explanation:</h4><p>To convert the CRASH_DATE columns to a date type we use the pandas function to_datetime(), passing the columns to change as a parameter.</p><pre>df[&#39;CRASH_DATE&#39;] = pd.to_datetime(df[&#39;CRASH_DATE&#39;])<br>df_crashes[&#39;CRASH_DATE&#39;] = pd.to_datetime(df_crashes[&#39;CRASH_DATE&#39;])</pre><p>We need to subset <em>df</em> and <em>df_crashes</em> to filter for crashes that occurred in 2017, 2018 and 2019. We use &gt;= to represent greater than or equal to and &lt;= to represent less than or equal to. Dates are in the format YYYY-MM-DD.</p><pre>df = df[(df[&#39;CRASH_DATE&#39;] &gt;= &#39;2018-01-01&#39;) &amp; (df[&#39;CRASH_DATE&#39;] &lt;= &#39;2020-12-31&#39;)]<br>df_crashes = df_crashes[(df_crashes[&#39;CRASH_DATE&#39;] &gt;= &#39;2018-01-01&#39;) &amp; (df_crashes[&#39;CRASH_DATE&#39;] &lt;= &#39;2020-12-31&#39;)]</pre><h3>Step 3. Display a plot showing the number of crashes that occur for each hour of the day.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0810bd7d0ed3769908dbb33097bec320/href">https://medium.com/media/0810bd7d0ed3769908dbb33097bec320/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bKuwDIcIKa67cUOc1SBaag.png" /></figure><h4>Code Explanation:</h4><p>We make the contents of the matplotlib and seaborn libraries available to our program. matplotlib and seaborn work together for creating visualizations in Python. I have a stylistic preference for my plots and set the seaborn theme style to darkgrid by calling the set_theme() method of seaborn. We also make the numpy library available to assist with labeling the axes of the plot.</p><pre>import matplotlib.pyplot as plt<br>import seaborn as sns<br>sns.set_theme(style=&#39;darkgrid&#39;)<br>import numpy as np</pre><p>To make plotting easier and more visually appealing, we create a new column in the DataFrame to represent the hour within which each crash occurred. 0 represents 12am to 1am, 1 represents 1am to 2am, all the way up to 23 which represents 11pm to 12am. To achieve this we use .dt.hour on the CRASH_DATE column to obtain the hour and place it into a new column, Hour.</p><pre>df[&#39;Hour&#39;] = df[&#39;CRASH_DATE&#39;].dt.hour</pre><p>Now it is time for us to plot . We specify 15 x 8 as the size of the plot and then call the barplot() method of seaborn. We pass it 5 parameters, each of which we will take in turn. The first parameter is the data we wish to plot: we group the records by our new Hour column and then count the number of unique CRASH_RECORD_ID in each group using the nunique() method. The second and third parameters are the x and y for the plot, which are the Hour and count of crashes respectively. The fourth parameter is the color palette chosen and the fifth specifies no line around the bars, a stylistic preference.</p><p>The remaining lines of code set the title and axes labels for the plot.</p><pre>plt.figure(figsize=(15,8))<br>s = sns.barplot(data=df.groupby(&#39;Hour&#39;)[&#39;CRASH_RECORD_ID&#39;].nunique().reset_index(), x=&#39;Hour&#39;, y=&#39;CRASH_RECORD_ID&#39;, palette=&#39;GnBu_r&#39;, linewidth=0)<br>s.set_title(&#39;Hourly Number of Reported Crashes in Chicago (2018 - 2020)&#39;, y=1.02, fontsize=14)<br>s.set_xlabel(&#39;Hour of Day&#39;, fontsize=13, labelpad=15)<br>s.set_ylabel(&#39;Number of Crashes&#39;, fontsize=13, labelpad=15)<br>plt.show()</pre><h3>Step 4. Name the make of vehicle that was involved in the most daylight crashes in August 2018. Remember that a crash can involve multiple vehicles.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03c992d065879742d0d89b1a839388eb/href">https://medium.com/media/03c992d065879742d0d89b1a839388eb/href</a></iframe><pre>CHEVROLET    49779<br>Name: MAKE, dtype: int64</pre><h4>Code Explanation:</h4><p>The first task we need to perform is to create a DataFrame containing only crashes that occurred during daylight lighting conditions. We start with <em>df</em> rather than <em>df_crashes</em> because we want to consider all vehicles involved in a crash. We do that by simply subsetting <em>df</em> for records with DAYLIGHT in the LIGHTING_CONDITION column and store the result in <em>df_daylight</em>.</p><pre>df_daylight = df[df[&#39;LIGHTING_CONDITION&#39;] == &#39;DAYLIGHT&#39;]</pre><p>Now that we have our source data ready, we call the value_counts() method on the MAKE column in the DataFrame to calculate the number of occurrences of each MAKE. Because we only want to know the make of vehicle with the most crashes, we use nlargest(1) to display just the data what we need.</p><pre>df_daylight[&#39;MAKE&#39;].value_counts().nlargest(1)</pre><h3>Step 5. Determine which weather condition was most prevalent for each type of crash.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73681bf8f459ab157e4def413485585c/href">https://medium.com/media/73681bf8f459ab157e4def413485585c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*B5VLSv0HZ8pwOGvuIPMvgQ.png" /></figure><h4>Code Explanation:</h4><p>We are able to use a single line of code for this step. Because it is a long line code, I will break it down in to parts for explanation.</p><p>We start by grouping the crash records in <em>df_crashes</em> by FIRST_CRASH_TYPE.</p><pre>df_crashes.groupby(&#39;FIRST_CRASH_TYPE&#39;)[&#39;WEATHER_CONDITION&#39;]</pre><p>Next, we want to determine which weather condition has the most crashes for each of the crash types. To do this we need to apply a function along an axis of the grouped data. Because we do not specify the axis, it defaults to 0, which is the index.</p><p>The lambda function calls the value_counts() method on each group (crash type) and counts the number of instances of each weather condition per group, in descending order. The call to the head() method then gives us the top weather condition for each crash type group.</p><pre>.apply(lambda x: x.value_counts().head(1))</pre><p>We use the the reset_index() method to reset the DataFrame index to the original one. We use it here to present the results in a more elegant manner. We pass the name parameter of ‘COUNT’ to name the column containing the count values.</p><pre>.reset_index(name=&#39;COUNT&#39;)</pre><p>Finally, we call the rename() method to rename the level_1 column as WEATHER, to make the output more readable.</p><pre>.rename(columns={&#39;level_1&#39;: &#39;WEATHER&#39;})</pre><h3>Step 6. Plot the primary contributing cause of reported crashes, from highest to lowest.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f97e7508f597a676827256d7ef7ff343/href">https://medium.com/media/f97e7508f597a676827256d7ef7ff343/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jhl5ui6m4bRh0LurGdGbvw.png" /></figure><h4>Code Explanation:</h4><p>Much of the code we use here is similar to the plot we created in step 3.</p><p>We specify 15 x 15 as the size of the plot and then call the countplot() method of seaborn. We pass it 3 parameters. The first is our <em>df_crashes</em> DataFrame. The second specifies that we wish to count the number of crashes for each primary contributory cause and by specifying <em>y</em> the bars will display horizontally on the plot. Because seaborn does not have an easy way to order the bars by size, for the third parameter <em>order</em> we tell seaborn to use the result of <em>df_crashes[‘PRIM_CONTRIBUTORY_CAUSE’].value_counts().index</em> to order the bars. This gives the descending order that we are looking for.</p><p>The remaining lines of code set the title and axes labels for the plot.</p><pre>plt.figure(figsize=(15, 15))<br>sns.countplot(data=df_crashes,  y=&#39;PRIM_CONTRIBUTORY_CAUSE&#39;, order = df_crashes[&#39;PRIM_CONTRIBUTORY_CAUSE&#39;].value_counts().index)<br>plt.title(&#39;Primary Contributing Cause of Reported Crashes in Chicago (2018 - 2020) &#39;, y=1.01, fontsize=14)<br>plt.xlabel(&#39;Number of Crashes&#39;, fontsize=13, labelpad=15)<br>plt.ylabel(&#39;Primary Contributing Cause&#39;, fontsize=13, labelpad=15)<br>plt.show();</pre><h3>Step 7. Display the 10 state license plates involved in the most crashes. Remember that a crash can involve multiple vehicles.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfb55a44a090c4bec0c9fd12b43c8b91/href">https://medium.com/media/cfb55a44a090c4bec0c9fd12b43c8b91/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*3A03pIy-2Nu1npWt7lnXOQ.png" /></figure><h4>Code Explanation:</h4><p>We start with <em>df</em> rather than <em>df_crashes</em> because we want to consider all vehicles involved in a crash. We group the records by LIC_PLATE_STATE and then count the number of VEHICLE_ID for each group. We use this field, because it is a unique identifier for each vehicle in lieu of not having the actual license plate data. Because we want the top 10, we call the .nlargest(10) method. Finally we call reset_index() and name the count column as COUNT.</p><pre>df.groupby(&#39;LIC_PLATE_STATE&#39;)[&#39;VEHICLE_ID&#39;].count().nlargest(10).reset_index(name=&#39;COUNT&#39;)</pre><h3>Step 8. Display the proportion of crashes in each month of 2019 where alcohol was determined to be the primary contributing cause.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1444c3e7498411c54de7e9ddf2fdf070/href">https://medium.com/media/1444c3e7498411c54de7e9ddf2fdf070/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*l1412adfO09bxfLuq1Ns_A.png" /></figure><h4>Code Explanation:</h4><p>Because we are only interested in 2019 crashes, we subset <em>df_crashes</em> using data filters to give us <em>df_alcohol</em>. With the second line of code we group the crashes by month and then count the number of crashes per month by calling the nunique() method, storing the result as <em>df_total</em> — this will be the denominator when we calculate the monthly proportions.</p><pre>df_alcohol = df_crashes[(df_crashes[&#39;CRASH_DATE&#39;] &gt;= &#39;2019-01-01&#39;) &amp; (df_crashes[&#39;CRASH_DATE&#39;] &lt;= &#39;2019-12-31&#39;)]<br>df_total = df_alcohol.groupby(df_alcohol[&#39;CRASH_DATE&#39;].dt.strftime(&#39;%m&#39;))[&#39;CRASH_RECORD_ID&#39;].nunique()</pre><p>Now we need the numerator, which is the number of alcohol related crashes per month. Firstly, we group the crashes by the primary contributing cause, but only if they contain the words ALCOHOL or DRINKING. A call to the contains() method, passing the words as a parameter gives us what we need. We use the | character to separate the two words. Next we group the resulting records by month and then count the number of crashes per month by calling the nunique() method again, storing the result back in to <em>df_alcohol</em>.</p><pre>df_alcohol = df_crashes[df_crashes[&#39;PRIM_CONTRIBUTORY_CAUSE&#39;].str.contains(&#39;ALCOHOL|DRINKING&#39;)]<br>df_alcohol = df_alcohol.groupby(df_alcohol[&#39;CRASH_DATE&#39;].dt.strftime(&#39;%m&#39;))[&#39;CRASH_RECORD_ID&#39;].nunique()</pre><p>Now that we have both the numerator and denominator, we can calculate the monthly proportions of crashes where alcohol was recorded as a primary contributing cause. We then call reset_index() like in other steps and use rename() to rename the columns for display purposes.</p><pre>df_proportion = df_alcohol / df_total * 100<br>df_proportion.reset_index().rename(columns={&#39;CRASH_DATE&#39;: &#39;MONTH&#39;, &#39;CRASH_RECORD_ID&#39;: &#39;PROPORTION&#39;})</pre><h3>Step 9. Determine whether snowmobiles or recreational off-highway vehicles were involved in more crashes.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91c73ae790202d25624c240c885ed363/href">https://medium.com/media/91c73ae790202d25624c240c885ed363/href</a></iframe><pre>Number of snowmobiles: 4</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/696f7e2dfdf306aab166670f79ac7d8d/href">https://medium.com/media/696f7e2dfdf306aab166670f79ac7d8d/href</a></iframe><pre>Number of recreational off-highway vehicles: 6</pre><h4>Code Explanation:</h4><p>For this step we use the same code twice, firstly looking for snowmobiles and secondly for recreational off-highway vehicles. We subset <em>df</em> for each vehicle type and use the len() function to count the number of records in the respective subsets.</p><pre>print(&#39;Number of snowmobiles:&#39;, str(len(df[df[&#39;VEHICLE_TYPE&#39;] == &#39;SNOWMOBILE&#39;])))<br>print(&#39;Number of recreational off-highway vehicles:&#39;, str(len(df[df[&#39;VEHICLE_TYPE&#39;] == &#39;RECREATIONAL OFF-HIGHWAY VEHICLE (ROV)&#39;])))</pre><h3>Step 10. Display a cluster map showing the locations of crashes involving a hit and run.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d63f12abfc2a9ddca93e659ed1bf47e8/href">https://medium.com/media/d63f12abfc2a9ddca93e659ed1bf47e8/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K-EfRCNW2MVfnq87GbdgKw.png" /></figure><h4>Code Explanation:</h4><p>We only wish to display the locations of crashes involving hit and runs, so we start by subsetting <em>df_crashes</em> to get the data we wish to plot, storing the result as <em>df_hitrun</em>. There are some records in the DataFrame without coordinates, so we remove them by using the notna() method.</p><pre>df_hitrun = df_crashes[df_crashes[&#39;HIT_AND_RUN_I&#39;] == &#39;Y&#39;]<br>df_hitrun = df_hitrun[df_hitrun[&#39;LONGITUDE&#39;].notna()]</pre><p>To display our map we are going to use Folium and an associated marker cluster plugin. We start by making the contents of the Folium module available to our program and importing the plugins. Folium is very powerful and requires little code to create an interactive map with great detail.</p><pre>import folium<br>from folium import plugins</pre><p>We need to instantiate a Folium map, by passing the GPS coordinates of Chicago and a zoom level, which we will set to 12. The latitude we will use is 41.8781 and the longitude -87.6798 (I found these with a quick Google search).</p><pre>m = folium.Map(location=[41.8781, -87.6798], zoom_start=12)</pre><p>We are creating a cluster map, so use the MarkerCluster plugin, adding it to our map with a call to the add_to() method and passing our Folium map <em>m</em> as a parameter.</p><p>Then for each crash in <em>df_hitrun</em> we create a marker. We iterate through <em>df_hitrun</em> using a for loop. The zip() function creates a tuple of latitude and longitude for each crash, creating a marker for each. Finally, we display the map <em>m</em>. As you zoom in and out of the map, the clusters resize interactively.</p><pre>hitrun = plugins.MarkerCluster().add_to(m)</pre><pre>for lat, lng in zip(df_hitrun[&#39;LATITUDE&#39;], df_hitrun[&#39;LONGITUDE&#39;]):<br>    folium.Marker(<br>        location=[lat, lng],<br>           icon=None,<br>    ).add_to(hitrun)<br>m</pre><p>I hope you have found this project a useful way to learn Python data analytics. Please share your feedback in the comments section.</p><p>Please also check out: <a href="https://towardsdatascience.com/learn-python-data-analytics-by-example-ny-parking-violations-e1ce1847fa2">Learn Python Data Analytics By Example: NYC Parking Violations</a> and <a href="https://towardsdatascience.com/learn-python-data-analytics-by-example-airline-arrival-delays-e26356e8ae6b">Learn Python Data Analytics By Example: Airline Arrival Delays</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4840f6f15ed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/learn-python-data-analytics-by-example-chicago-traffic-crashes-4840f6f15ed">Learn Python Data Analytics by Example — Chicago Traffic Crashes</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn Python Data Analytics by Example — Airline Arrival Delays]]></title>
            <link>https://medium.com/data-science/learn-python-data-analytics-by-example-airline-arrival-delays-e26356e8ae6b?source=rss-9addc0db62fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/e26356e8ae6b</guid>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Nick Cox]]></dc:creator>
            <pubDate>Mon, 25 Jan 2021 18:25:34 GMT</pubDate>
            <atom:updated>2021-01-25T18:25:34.137Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learn Python Data Analytics by Example — Airline Arrival Delays</h3><h4>A fun project and detailed walkthrough of data analytics steps to help you learn Python, pandas, matplotlib and Basemap</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3FbJyZIJXYtP3r9x" /><figcaption>Photo by <a href="https://unsplash.com/@chuttersnap?utm_source=medium&amp;utm_medium=referral">CHUTTERSNAP</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>While working towards my Master’s in Business Analytics, I found that learning by example is the best way for me to learn Python data analytics. Being given a dataset and a set of coding tasks is much more beneficial than reading a textbook or listening to a professor.</p><p>I want to share this method of learning with others who will also benefit. All you need is a Python development environment (I recommend <a href="https://jupyter.org/">Jupyter Notebook</a>) and a willingness to learn and have fun.</p><p>Included in this article is a list of data analytics tasks, followed by a detailed walkthrough of how to complete the tasks. Please try to complete the tasks yourself before reading through the walkthrough — you will get more out of it that way. Do keep in mind that there are many many ways to solve coding problems, so your code likely will not match mine word for word and that is okay.</p><p>Please also check out: <a href="https://towardsdatascience.com/learn-python-data-analytics-by-example-ny-parking-violations-e1ce1847fa2">Learn Python Data Analytics By Example: NYC Parking Violations</a></p><h3>Project Description</h3><p>For this project we will use a dataset of about 40,000 records, which represent flight arrival delays for 18 airlines in the United States. Each row in the dataset represents a summary of delay data for a carrier-airport pair for the specified month. The dataset was created in January 2021 and contains data from January 1, 2018 to December 31, 2019 sourced from the <a href="https://www.transtats.bts.gov/OT_Delay/OT_DelayCause1.asp">Bureau of Transportation Statistics</a>.</p><p>You will need to install the <a href="https://pandas.pydata.org/">pandas</a>, <a href="https://matplotlib.org/">matplotlib</a> and <a href="https://matplotlib.org/basemap/index.html">Basemap</a> libraries, if you do not already have them.</p><h3>Data Analytics Tasks</h3><p>Please perform the following tasks in Python using the <em>delays_2018.csv</em>, <em>delays_2019.csv</em> and <em>airport_coordinates.csv</em> datasets available from the <a href="https://github.com/nickdcox/learn-airline-delays">GitHub repo</a>.</p><ol><li>Read the CSV files containing the airline delay data into a single DataFrame. Then display the total number of rows imported.</li><li>Change the <em>date</em> column to date format YYYY-M (e.g. 2018–1). Then perform exploratory data analysis on the imported dataset to identify invalid data — write code to remove the impacted rows. Finally, display the number of rows remaining.</li><li>Display a list of all Tennessee airports that appear in the dataset.</li><li>Import the coordinates dataset and merge it with the existing dataset. Plot the coordinates of all airports on a map (hint: use Matplotlib and Basemap).</li><li>Display the number of diverted flights for each carrier-airport pair.</li><li>Display how many arrivals into JFK in 2019 encountered both weather and carrier delays.</li><li>Display the airline with the most flight cancellations as a percentage of total arriving flights.</li><li>Determine the overall average number of delays per airport.</li><li>Display the three carriers with the lowest number of delayed flights.</li><li>Request that the user input an airline. Then plot the monthly number of national air system (NAS) delay minutes for that airline. Display whether the trend is increasing or decreasing over the last 2 months.</li></ol><h3>Data Dictionary (delays_2018.csv, delays_2019.csv)</h3><p>Each row in the datasets represents a summary of delay data for a carrier-airport pair for the specified month. For example, a row may represent delay data for May 2018 for American Airlines flights arriving into JFK airport in New York City.</p><p>When multiple causes are assigned to one delayed flight, each cause is prorated based on delayed minutes it is responsible for. The numbers are rounded and may not add up to the total.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r-Qgom-7vHyGHYxO7K6Mxw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tZyIqSNUhxhYL_g9" /><figcaption>Photo by <a href="https://unsplash.com/@jonecohen?utm_source=medium&amp;utm_medium=referral">Johnny Cohen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Step 1: Read the CSV files containing the airline delay data into a single DataFrame. Then display the total number of rows imported.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa2d900aa377aa2428fe0641277228cf/href">https://medium.com/media/fa2d900aa377aa2428fe0641277228cf/href</a></iframe><pre>Number of Rows: 41177</pre><h4>Code Explanation:</h4><p>We start by making the contents of the pandas module available to our program. pandas is an easy to use open source data analysis and manipulation tool, built on top of the Python programming language. We will use it extensively throughout this project.</p><pre>import pandas as pd</pre><p>We import the contents of the <em>delays_2018.csv</em> file by calling the read_csv() method and store it in a DataFrame, named <em>df_18</em>. A DataFrame is a two-dimensional data structure with labeled axes, consisting of data, rows and columns. Think of it like a table built in Microsoft Excel or Microsoft Access. We then repeat the same action for the <em>delays_2019.csv</em> file, naming it <em>df_19</em>.</p><pre>df_18 = pd.read_csv(&#39;delays_2018.csv&#39;)<br>df_19 = pd.read_csv(&#39;delays_2019.csv&#39;)</pre><p>To combine the two DataFrames into a single DataFrame, we call the concat() method of pandas, which is short for concatenate. We pass two parameters: the first is a list containing the names of the two DataFrames that we want to concatenate and the second is telling pandas to ignore the existing indexes in the two DataFrames, thus creating a new one.</p><pre>df = pd.concat([df_18, df_19], ignore_index=True)</pre><p>We use the print() function to print the string ‘Number of Rows:’ followed by the number of rows in the DataFrame. The parameter that we pass to the print() function is made up of two parts. The first is the string ‘Number of Rows: ‘ surrounded in single quotes, denoting it as a string. The second part of the parameter is calculating the number of rows in <em>df</em>. We use the len() function to tell us the number of rows in <em>df</em>, then wrap it in a call to the str() method to convert the length into a string. Finally, the + concatenates (or joins) the two string parts together. All parts of the parameter passed to the print() function must be of type string.</p><pre>print(&#39;Number of Rows: &#39; + str(len(df)))</pre><h3>Step 2: Change the date column to date format YYYY-M (e.g. 2018–1). Then perform exploratory data analysis on the imported dataset to identify invalid data — write code to remove the impacted rows. Finally, display the number of rows remaining.</h3><p>The following data is considered to be invalid:</p><ul><li>Year: values that are not 2018 or 2019</li><li>Arriving Flights: airports with no arriving flights (blank values in <em>arr_flights</em> column)</li><li>Carrier: blank values</li><li>Airport: blank values</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/172dcb1450ba0abfbb9ac74ef1b3a720/href">https://medium.com/media/172dcb1450ba0abfbb9ac74ef1b3a720/href</a></iframe><pre>Number of Rows: 41077</pre><h4>Code Explanation:</h4><p>Before we look for invalid data, we are going to convert the <em>date</em> column from the string data type to date. To do this we call the to_datetime() method of pandas. As parameters, we pass the existing <em>date</em> column and the format of the dates, even though they are stored as strings. %Y-%m represents YYYY-M, for example 2018–1. If we stopped here, then pandas would format the date with year, month, day and time, which we do not want. To avoid this we use .dt.strftime(‘%Y-%m’) to force the date format that we need.</p><pre>df[&#39;date&#39;] = pd.to_datetime(df[&#39;date&#39;], format=&#39;%Y-%m&#39;).dt.strftime(&#39;%Y-%m&#39;)</pre><p>We need to subset <em>df</em> to filter out records with invalid data. We are able to apply multiple parameters at once by wrapping each in parentheses and using the &amp; character between them. We use &gt;= to represent greater than or equal to and &lt;= to represent less than or equal to. For the arrival flights, carrier, carrier name, airport and airport name columns, we need to check for null values by calling the notnull() method.</p><pre>df = df[(df[&#39;date&#39;] &gt;= &#39;2018-01&#39;) &amp; (df[&#39;date&#39;] &lt;= &#39;2019-12&#39;) &amp; (df[&#39;arr_flights&#39;].notnull())<br>              &amp; (df[&#39;carrier&#39;].notnull()) &amp; (df[&#39;carrier_name&#39;].notnull()) <br>              &amp; (df[&#39;airport&#39;].notnull()) &amp; (df[&#39;airport_name&#39;].notnull())]</pre><p>We use the print() function in exactly the same way as Step 1 above.</p><pre>print(&#39;Number of Rows: &#39; + str(len(df)))</pre><h3>Step 3. Display a list of all Tennessee airports that appear in the dataset.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6368ed53bf32ace85b432d54533b1b7/href">https://medium.com/media/c6368ed53bf32ace85b432d54533b1b7/href</a></iframe><pre>Tennessee Airports:<br>{&#39;Chattanooga, TN: Lovell Field&#39;, &#39;Memphis, TN: Memphis International&#39;, &#39;Bristol/Johnson City/Kingsport, TN: Tri Cities&#39;, &#39;Nashville, TN: Nashville International&#39;, &#39;Knoxville, TN: McGhee Tyson&#39;}</pre><h4>Code Explanation:</h4><p>To start with, we need to identify rows in the dataset with flights arriving into a Tennessee airport. To do this we need to apply a function along an axis of the DataFrame. Because we do not specify the axis, it defaults to 0, which is the index. Therefore, we will iterate down the airport name column.</p><p>The lambda function calls the find() method on each airport name in order to find the substring <em>TN</em> within. If the substring <em>TN</em> is not found in the airport name, a value of -1 is placed into the new TN column. If <em>TN</em> is found, an intger other than -1 is placed into the TN column.</p><pre>df[&#39;TN&#39;] = df[&#39;airport_name&#39;].apply(lambda x: x.find(&#39;TN&#39;))</pre><p>Now that we have identified all of the airports in Tennessee, we need to create a list of them, but without duplicates. We can use the set() function to do this and as a parameter we pass a subset of the DataFrame containing only the rows with airport names containing <em>TN</em>, as designated by a -1 in the TN column.</p><pre>airports = set(df[df[&#39;TN&#39;] != -1][&#39;airport_name&#39;])</pre><p>We then print out the list of Tennessee airports.</p><pre>print(&#39;Tennessee Airports:&#39;)<br>print(airports)</pre><h3>Step 4. Import the coordinates dataset and merge it with the existing dataset. Plot the coordinates of all airports on a map (hint: use Matplotlib and Basemap).</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/760f22650aa287757918ce2ec4438b3c/href">https://medium.com/media/760f22650aa287757918ce2ec4438b3c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b1qq58ZjiLCi7cYBzjfMAg.png" /></figure><h4>Code Explanation:</h4><p>Please bear with me on this one as there is a lot of code that requires explanation. The effort is worthwhile, because you will learn how to display maps and plot points on them using coordinates.</p><p>We import the contents of the <em>airport_coordinates.csv</em> file by calling the read_csv() method and store it in a DataFrame, named <em>df_coords</em>.</p><pre>df_coords = pd.read_csv(&#39;airport_coordinates.csv&#39;)</pre><p>We are now going to create a new DataFrame to represent all airports in the dataset and their coordinates. We subset <em>df</em> to include only the columns for airport and airport name. By adding a call to the drop_duplicates() function, we are able to create a DataFrame with each airport only occurring once. Finally, with a call to the reset_index() function we reset the DataFrame index to the original one.</p><pre>df_airports = df[[&#39;airport&#39;, &#39;airport_name&#39;]].drop_duplicates().reset_index(drop=True)</pre><p>Now, we use the merge() function of pandas to merge the <em>df_airport</em> and <em>df_coords</em> DataFrames to create our final DataFrame of airports with their respective coordinates. The first two parameters are the DataFrames that we are merging and the third is the column that is common in both DataFrames — airport, which is the three character designator for the arrival airport.</p><pre>df_airports = pd.merge(df_airports, df_coords, on=&#39;airport&#39;)</pre><p>The following line of code may or may not be required for you. I encountered an error when running the <em>from mpl_toolkits.basemap import Basemap</em> line of code and the solution was to add the following.</p><pre>import os<br>os.environ[&quot;PROJ_LIB&quot;] = &quot;C:\\Users\\Nick\\anaconda3\\envs\\sandbox\\Library\\share\\basemap&quot;;</pre><p>We make the contents of the matplotlib library available to our program. matplotlib is a comprehensive library for creating visualizations in Python.</p><p>We then make the mpl_toolkits.basemap library available to our program. Basemap is a library for plotting 2D data on maps and the one that we will use to plot the map of airports in the dataset.</p><pre>import matplotlib.pyplot as plt<br>from mpl_toolkits.basemap import Basemap</pre><p>We specify the size of our map plot as 16 x 16. Next, we create an instance of the Basemap class, passing a large group of parameters. The first four (llcrnclon, llcrnrlat, urcrnrlon and urcrnrlat) specify the longitude of lower left hand corner, the latitude of lower left hand corner, the longitude of upper right hand corner and the latitude of upper right hand corner of the plot. For this project, we are specifying coordinates that give us a map of the United States. For the project parameter we are passing lcc (Lambert Conformal), which is typically used for aeronautical charts. The remaining parameters are specific to the selection of lcc.</p><p>For a more detailed description of the parameters, please refer to the official <a href="https://matplotlib.org/basemap/api/basemap_api.html">Basemap documentation</a>.</p><pre>fig = plt.figure(figsize=(16, 16))<br>m = Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49,<br>        projection=&#39;lcc&#39;,lat_1=32,lat_2=45,lon_0=-95)</pre><p>The above code provides us with the right coordinates on the plot, but does not provide us with the outline of the United States and its states. We need to utilize shapefiles for this. The shapefiles required for this project can be found on the <a href="https://github.com/matplotlib/basemap/tree/master/examples">Basemap GitHub repo</a>. Look for st99_d00.dbf, st99_d00.shp and st99_d00.shx — place these files in the same folder as your other source files.</p><p>We call the readshapefile() method on our Basemap object and pass it two parameters. The first is the name of the shapefile that we downloaded and the second is the name we assign to the attribute to hold the shapefile map points.</p><pre>m.readshapefile(&#39;st99_d00&#39;, name=&#39;states&#39;)</pre><p>All that remains now is for us to plot the coordinates on the map, by calling the scatter() method of our Basemap object. The parameters passed are the longitude and latitude coordinates of the airports in our <em>df_airports</em> DataFrame and the latlon parameter equal to True which flags that our coordinates are in degrees. We specify .values to pass only the values from the DataFrame, thus excluding the indexes.</p><pre>m.scatter(df_airports[&#39;long&#39;].values, df_airports[&#39;lat&#39;].values, latlon=True)<br>plt.show()</pre><h3>Step 5. Display the number of diverted flights for each carrier-airport pair.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2685445b3888efb8ac66e237ba464dd8/href">https://medium.com/media/2685445b3888efb8ac66e237ba464dd8/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lQCeJSy_V79F3WH1PQF9sQ.png" /></figure><h4>Code Explanation:</h4><p>Having created an awesome map plot, we will now turn to another powerful pandas function — crosstab. Cross tabulation is a method to quantitatively analyze the relationship between multiple variables. In this project we want to determine the number of diverted flights for each carrier-airport pair, for example: how many American Airlines flights scheduled to arrive at JFK airport in New York City were diverted? Using the crosstab() function of pandas we are able to create a single table that displays this for all carrier-airport pairs in our dataset.</p><p>The first parameter that we pass is the carrier column from <em>df</em>, which will be the rows in our crosstab. The second is the airport column, which will be the columns in our crosstab. The values that we want to display in the crosstab are the number of diverted flights, the arr_diverted column. With the fourth parameter, we specify that we want to sum the number of diversions for each carrier-airport pair — this is required because each carrier-airport pair appears multiple times in the dataset, once per month. Finally, we cap off the line of code with a call to the fillna() function to replace NaN values with blanks — this removes noise from the resulting crosstab and eases readability.</p><p>Only one line of code, but a very powerful one.</p><pre>pd.crosstab(df[&#39;carrier&#39;], df[&#39;airport&#39;], values=df[&#39;arr_diverted&#39;], aggfunc=&#39;sum&#39;).fillna(&#39;&#39;)</pre><h3>Step 6. Display how many arrivals into JFK in 2019 encountered both weather and carrier delays.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9c8bf20acbaf684e64f586f6ec40e08/href">https://medium.com/media/d9c8bf20acbaf684e64f586f6ec40e08/href</a></iframe><pre>Number of Delays: 6919.429999999999</pre><h4>Code Explanation:</h4><p>We used similar code to this in Step 2 above. We are subsetting <em>df</em> to get only those rows representing flights arriving into JFK in 2019 that had both carrier and weather delays. We store the result as <em>df_f</em>.</p><pre>df_f = df[(df[&#39;date&#39;] &gt;= &#39;2019-01&#39;) &amp; (df[&#39;date&#39;] &lt;= &#39;2019-12&#39;) &amp; (df[&#39;airport&#39;] == &#39;JFK&#39;) <br>          &amp; (df[&#39;carrier_ct&#39;] &gt; 0) &amp; (df[&#39;weather_ct&#39;] &gt; 0)]</pre><p>The total number of delays is the sum of carrier and weather delays, which we print out. Remember that we need to convert the sums to string before we can print them.</p><pre>print(&quot;Number of Delays: &quot; + str(df_f[&#39;carrier_ct&#39;].sum()  + df_f[&#39;weather_ct&#39;].sum()))</pre><h3>Step 7. Display the airline with the most flight cancellations as a percentage of total arriving flights.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9377f036380d654cabd7e71ea55dad36/href">https://medium.com/media/9377f036380d654cabd7e71ea55dad36/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*ywfQj6QAkDdm8vA6FeStaQ.png" /></figure><h4>Code Explanation:</h4><p>To calculate cancellation percentages, we need DataFrames representing both the numerator (cancelled flights) and the denominator (all flights). We start with the latter: We group the rows in <em>df</em> by the carrier name and sum the number of arriving flights for each carrier. We pass the name parameter of ‘num_arrived’ to the reset_index() function to name the column containing the sum values.</p><p>Then we group the rows in <em>df</em> by the carrier name and sum the number of cancelled arrivals for each carrier. We use reset_index() again. Finally, we create the <em>df_cancelled</em> DataFrame by merging the DataFrame using the common column of ‘carrier_name’.</p><pre>df_flights = df.groupby(&#39;carrier_name&#39;)[&#39;arr_flights&#39;].sum().reset_index(name=&#39;num_arrived&#39;)<br>df_cancelled = df.groupby(&#39;carrier_name&#39;)[&#39;arr_cancelled&#39;].sum().reset_index(name=&#39;num_cancelled&#39;)<br>df_cancelled = pd.merge(df_cancelled, df_flights, on=&#39;carrier_name&#39;)</pre><p>We can then calculate the percentage of cancelled flights per carrier by dividing the number of cancelled flights by the number of arriving flights for each carrier.</p><pre>df_cancelled[&#39;proportion&#39;] = df_cancelled[&#39;num_cancelled&#39;] / df_cancelled[&#39;num_arrived&#39;] * 100</pre><p>As a final step, we sort the values in descending order by calling the sort_values() function and then using head(1) to display only the carrier with the highest percentage of cancelled flights.</p><pre>df_cancelled.sort_values(by=[&#39;proportion&#39;], ascending=False).head(1)</pre><h3>Step 8. Determine the overall average number of delays per airport.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d609fa1c9b9e25816bbfe566d3e5f449/href">https://medium.com/media/d609fa1c9b9e25816bbfe566d3e5f449/href</a></iframe><pre>Average Number of Delays per Airport: 7544.997245179064</pre><h4>Code Explanation:</h4><p>To calculate the overall average number of delays per airport, we first need to calculate the number of delays per airport and then find the average of those values. We are able to achieve this in one line of code. We group the rows in <em>df</em> by airport and sum the number of delayed arrivals into each airport. By adding a call to the mean() function on the end, we calculate the average of the sums.</p><pre>avg_delays = df.groupby(&#39;airport&#39;)[&#39;arr_del15&#39;].sum().mean()</pre><p>We then simply print out the result.</p><pre>print(&#39;Average Number of Delays per Airport: &#39; + str(avg_delays))</pre><h3>Step 9. Display the three carriers with the lowest number of delayed flights.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e62e73c1ae49cd2bd477c57f23fe85c3/href">https://medium.com/media/e62e73c1ae49cd2bd477c57f23fe85c3/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*09pKlJ4pNb2zSmh9aeaBFA.png" /></figure><h4>Code Explanation:</h4><p>We group the rows in <em>df</em> by carrier and sum the number of delayed arrivals per carrier. We are only interested in the three carriers with the lowest number of delayed arrivals, so use .nsmallest(3) to give us the three lowest carriers. For display purposes, we pass the name parameter in our call to reset_index().</p><pre>df.groupby(&#39;carrier&#39;)[&#39;arr_del15&#39;].sum().nsmallest(3).reset_index(name=&#39;num_delays&#39;)</pre><h3>Step 10. Request that the user input an airline. Then plot the monthly number of national air system (NAS) delay minutes for that airline. Display whether the trend is increasing or decreasing over the last 2 months.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/975ef089c88e3af9664b543e14d5b56a/href">https://medium.com/media/975ef089c88e3af9664b543e14d5b56a/href</a></iframe><pre>What airline (9E, AA, AS, B6, DL, EV, F9, G4, HA, MQ, NK, OH, OO, UA, VX, WN, YV, YX)? EV</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10c5bc1512a36e3b186cd64d03bad9c4/href">https://medium.com/media/10c5bc1512a36e3b186cd64d03bad9c4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oTDEnAnzaa7V43AEAQEgmQ.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7694cd22de97c6312fc364ef4a1ee40/href">https://medium.com/media/e7694cd22de97c6312fc364ef4a1ee40/href</a></iframe><pre>Total NAS delay minutes for EV are increasing.</pre><h4>Code Explanation:</h4><p>We use input() to request the user to input a carrier and save the value in the <em>airline</em> variable. To keep the code simple, we are not performing any validation checks on what the user is inputting and therefore we expect that they will only input a valid value.</p><pre>airline = input(&quot;What airline (9E, AA, AS, B6, DL, EV, F9, G4, HA, MQ, NK, OH, OO, UA, VX, WN, YV, YX)? &quot;)</pre><p>We subset <em>df</em> according to the carrier input by the user and because we are only interested in national air system (NAS) delays we filter on that too to exclude rows without any NAS delays. We store the result as <em>df_nas</em>.</p><pre>df_nas = df[(df[&#39;carrier&#39;] == airline) &amp; (df[&#39;nas_delay&#39;] &gt; 0)]</pre><p>We group the rows in <em>df_nas</em> by date and sum the number of NAS delays for each month.</p><pre>df_nas = df_nas.groupby(&#39;date&#39;)[&#39;nas_delay&#39;].sum()</pre><p>Now it is time for us to plot the results using matplotlib. We specify 16 x 8 as the size of the plot, <em>df_nas</em> as the data source for the plot and because there are a lot of labels on the x axis, we rotate them 85 degrees to display them neatly without overlap.</p><pre>plt.figure(figsize=(16, 8))<br>plt.plot(df_nas)<br>plt.xticks(rotation=85)<br>plt.show()</pre><p>The final step in the project is to display whether NAS delays are increasing or descreasing in the past two months for the carrier selected by the user. We can use simple if-else logic to print a statement of either increasing or decreasing. We utilize iloc integer based indexing to access the last value in <em>df_nas</em> (-1) and the second to last value (-2) and compare them. If the last value is greater than the second to last value, then the delays are increasing, otherwise the delays are decreasing.</p><pre>if df_nas.iloc[-1] &gt; df_nas.iloc[-2]:<br>    print(&#39;Total NAS delay minutes for &#39; + airline + &#39; are increasing.&#39;)<br>else:<br>    print(&#39;Total NAS delay minutes for &#39; + airline + &#39; are decreasing.&#39;)</pre><p>I hope you have found this project a useful way to learn Python data analytics. Please share your feedback in the comments section.</p><p>Please also check out: <a href="https://towardsdatascience.com/learn-python-data-analytics-by-example-ny-parking-violations-e1ce1847fa2">Learn Python Data Analytics By Example: NYC Parking Violations</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e26356e8ae6b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/learn-python-data-analytics-by-example-airline-arrival-delays-e26356e8ae6b">Learn Python Data Analytics by Example — Airline Arrival Delays</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Did You Have Coronavirus and Not Even Know It? I Know Who Did!]]></title>
            <link>https://medium.datadriveninvestor.com/did-you-have-coronavirus-and-not-even-know-it-i-know-who-did-77200e76149e?source=rss-9addc0db62fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/77200e76149e</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[covid19]]></category>
            <dc:creator><![CDATA[Nick Cox]]></dc:creator>
            <pubDate>Fri, 15 Jan 2021 14:47:55 GMT</pubDate>
            <atom:updated>2021-01-18T09:53:18.674Z</atom:updated>
            <content:encoded><![CDATA[<h4>A detailed analysis of Amazon reviews for scented candle products, using Python &amp; natural language processing.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pQ3G0vwp6nzEBKh_" /><figcaption>Photo by <a href="https://unsplash.com/@tobiasrehbein?utm_source=medium&amp;utm_medium=referral">Tobias Rehbein</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In November 2020, I saw an interesting <a href="https://twitter.com/kate_ptrv/status/1332398737604431874?lang=en">tweet </a>about scented candles being an unexpected victim of the coronavirus. This caught my interest and I embarked on a project to determine if there was any truth to the claim.</p><p>In this article, I present a brief summary of the analysis I undertook, but primarily I present you with the results of my project. I was surprised at how obvious the conclusions were.</p><p>All code for this project can be found in this <a href="https://github.com/nickdcox/nlp-sentiment-coronavirus">GitHub repo</a>.</p><p><strong>Project Objective:</strong> To use natural language processing and sentiment analysis to research the impact of the coronavirus pandemic on the review of Yankee Candle products on Amazon.</p><p><strong>Hypothesis:</strong> That average review ratings and sentiment for Yankee Candle products on Amazon have decreased in 2020, when compared to previous years, due to the common coronavirus symptom of a loss of smell. My assertion is that purchasers of Yankee Candles blame the manufacturer for a lack of scent in the product, without realizing it is their own health condition that is at fault.</p><p><strong>Tools Used:</strong> Python, Pandas, Scrapy, NLTK, Gensim, TextBlob, VADER Sentiment Analysis, scikit-learn, Matplotlib, Seaborn</p><h3>Web Scraping &amp; Data Cleaning</h3><p>For this project I needed to create a dataset of product reviews and ratings by scraping Yankee Candle product pages on Amazon. To obtain my target of 30,000 reviews I needed to scrape review pages for 10 different Yankee Candle products. I utilized <a href="https://scrapy.org/">Scrapy </a>for this and you can find the code I used in the <a href="https://github.com/nickdcox/nlp-sentiment-coronavirus">GitHub repo</a>.</p><p>I built some logic into the spider itself, so the data was relatively clean from the outset. Otherwise, I just needed to drop reviews with no comments and change the date field to a date format using pandas to_datetime().</p><p>Although I scraped reviews as far back as 2008, for this project I focused on reviews posted between January 1, 2017 and December 31, 2020.</p><h3>Feature Extraction &amp; Text Pre-Processing</h3><p>Amazon reviews have an associated rating from 1 to 5, with 5 being the highest and best rating. For this project I defined good reviews as reviews with a rating of 4 or 5, and bad reviews as those with a rating of 3 or less.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/0*Fy3s5zU26ZJFZ8sQ.png" /><figcaption>Source: Amazon.com</figcaption></figure><p>At this point I was ready to pre-process my dataset, in readiness for sentiment analysis. Text pre-processing transforms text into a more digestible form so that machine learning algorithms can perform better. This included changing all of the review comments to lowercase characters, removing punctuation, HTML and emojis, correcting spelling and removing stop words (the most common words in a language, e.g., a, and, but, how, or, what). At this point, lemmatization was performed to reduce the words to their root form.</p><h3>Exploratory Data Analysis (EDA)</h3><p>In this step I used summary statistics and visualizations to better understand the dataset, discover patterns and identify anomalies.</p><p>A key part of my work here was to determine the polarity of the review comments using the <a href="https://github.com/cjhutto/vaderSentiment">VADER </a>Sentiment Intensity Analyzer. Polarity is a means to quantify sentiment with a positive or negative value, to help us understand an opinion expressed in text. It is measured in a range of -1 to 1, where 1 means a positive statement and -1 means a negative statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pB7z2bpnH51ISpB70WNwRw.png" /></figure><ul><li>The polarity of Yankee Candle product reviews on Amazon is generally positive, with a majority of reviews scoring between 0.5 and 1.0 (VADER Compound Score). Most reviews with a negative polarity score are just below 0, so could be said to be neutral rather than negative.</li><li>As to be expected, bad reviews (rating &lt;= 3) on average have a lower polarity score than good reviews (rating &gt;= 4) do.</li></ul><h3>Hypothesis Testing</h3><p>Now for the meat and potatoes of my project. As a reminder, here was my hypothesis:</p><p><strong>Hypothesis:</strong> That average review ratings and sentiment for Yankee Candle products on Amazon have decreased in 2020, when compared to previous years, due to the common coronavirus symptom of a loss of smell. My assertion is that purchasers of Yankee Candles blame the manufacturer for a lack of scent in the product, without realizing it is their own health condition that is at fault.</p><p>What follows are the visualizations that I produced with <a href="https://matplotlib.org/">matplotlib </a>and <a href="https://seaborn.pydata.org/">Seaborn </a>and the insights I obtained from them.</p><h4>Trend of Good vs. Bad Reviews</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1BYqryKnXv0yjJC_ozum6Q.png" /></figure><ul><li>In the above line plot, there is a clear and significant decrease in good reviews for Yankee Candle products and a corresponding increase in bad reviews beginning in April 2020.</li><li>In July 2020 there were almost an equal number of good reviews and bad reviews for Yankee Candle products, for the first and only time.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qK-ZY6zPoXUlHObZ3zsO-g.png" /></figure><ul><li>In the above line plot, it can be seen from April to September 2020 that the gap between the number of good reviews for Yankee Candle products and the number of bad reviews narrows, when compared to earlier months.</li></ul><h4>Trend of Monthly Average Review Rating</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G2NKk5Bf-iRIM5rAYTRR8Q.png" /></figure><ul><li>In the above line plot, there is an obvious deterioration in the average review rating for Yankee Candle products in 2020, from the onset of the coronavirus pandemic. Review ratings have dropped from an average of nearly 4.5 in January 2020 to between 3.3 and 3.6 in the subsequent months.</li></ul><h3>Trend of Monthly Average Sentiment and Monthly Average Review Rating</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*csdt67GY1HDs1_FZgDeegA.png" /></figure><ul><li>In the above line plot, monthly average review ratings for Yankee Candle products closely track the average sentiment of the reviews, as measured by the VADER Sentiment Intensity Analyzer. This includes in Fall each year when there is a cyclical dip and in 2020 during the coronavirus pandemic.</li></ul><h3>Trend of Monthly Average Sentiment Components</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bHWd4Qe_ZtU46jZMRhsebQ.png" /></figure><ul><li>In the above line plot, the average VADER positive, neutral and negative scores remain relatively stable until 2020, when the positive score starts to trend down and both the neutral and negative scores trend up. This is a reflection of the overall decrease in sentiment expressed in the reviews of Yankee Candle products on Amazon in 2020.</li><li>The cyclical Fall dip can also be observed in this line plot. It appears that the Fall dip reflects a decrease in the average positive score and a corresponding increase in the average neutral score for the month. There is no material change in the average negative score during the Fall dip. So, it could be said that sentiment expressed in reviews becomes more neutral and less positive, but not more negative.</li></ul><h3>Sentiment of Reviews Before and During Pandemic</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KHSQbcfOXXWjt0igX9ux6g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kP2faxnXt_brRAwt1Jrf2Q.png" /></figure><ul><li>In the above plots it is evident that there is a material shift to the left in the distribution of the sentiment of reviews during the pandemic when compared to before the pandemic. This is consistent with the decrease in the average review ratings, although the shift is not as pronounced as I had expected.</li></ul><h3>Nature of Reviews Before and During Pandemic</h3><p>I used the scikit-learn <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html">Count Vectorizer</a> to identify groups of 2 and 3 words, known as bigrams and trigrams, that frequently appeared together in the review comments. I then compared the bigrams and trigrams from reviews before the pandemic to those found in reviews during the pandemic.</p><ul><li>Four of the top 50 bigrams/trigrams in Yankee Candle product reviews on Amazon before the coronavirus pandemic relate to a lack of scent (scent not, no scent, not strong, not smell), whereas 7 of the top 50 in product reviews during the pandemic relate to a lack of scent (no scent, scent not, not strong, not smell, no smell, barely smell, smell not).</li><li>The ratio of the lack of scent ngrams appearing in product reviews before the pandemic is 1,255 occurrences of the ngrams to 20,806 product reviews (0.06:1), whereas during the pandemic the ratio is 1,097 occurrences of the ngrams to 10,315 product reviews (0.11:1), a near doubling.</li></ul><h3>Coronavirus or Candles Without a Scent?</h3><p>Based on my analysis, we can accept the hypothesis that the review ratings and sentiment for Yankee Candle products on Amazon have decreased in 2020, when compared to previous years and this is likely due to the common coronavirus symptom of a loss of smell.</p><p>I hope you have found this project as interesting as I did. Please share your feedback in the comments section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77200e76149e" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/did-you-have-coronavirus-and-not-even-know-it-i-know-who-did-77200e76149e">Did You Have Coronavirus and Not Even Know It? I Know Who Did!</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[Learn Python Data Analytics By Example: NY Parking Violations]]></title>
            <link>https://medium.com/data-science/learn-python-data-analytics-by-example-ny-parking-violations-e1ce1847fa2?source=rss-9addc0db62fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1ce1847fa2</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Nick Cox]]></dc:creator>
            <pubDate>Tue, 12 Jan 2021 23:45:17 GMT</pubDate>
            <atom:updated>2021-01-25T18:22:40.133Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learn Python Data Analytics By Example: NYC Parking Violations</h3><h4>A fun project and detailed walkthrough of data analytics steps to help you learn Python, pandas and matplotlib.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tQzGw38D21nd9v49" /><figcaption>Photo by <a href="https://unsplash.com/@imjoshnewton?utm_source=medium&amp;utm_medium=referral">Josh Newton</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>While working towards my Master’s in Business Analytics, I found that learning by example was the best way for me to learn Python data analytics. Being given a dataset and a set of coding tasks is much more beneficial than reading a textbook or listening to a professor.</p><p>I want to share this method of learning with others who will also benefit. All you need is a Python development environment (I recommend <a href="https://jupyter.org/">Jupyter Notebook</a>) and a willingness to learn and have fun.</p><p>Included in this article is a list of data analytics tasks, followed by a detailed walkthrough of how to complete the tasks. Please try to complete the tasks yourself before reading through the walkthrough — you will get more out of it that way. Do keep in mind that there are many many ways to solve coding problems, so your code likely will not match mine word for word.</p><h3>Project Description</h3><p>For this project we will use a dataset of 50,000 parking violations issued in New York City during the 2021 fiscal year. The dataset was created in January 2021 and contains data from April 1 to November 30, 2020 sourced from <a href="https://data.cityofnewyork.us/City-Government/Parking-Violations-Issued-Fiscal-Year-2021/pvqr-7yc4">NYC Open Data</a>.</p><p>You will need to install the <a href="https://pandas.pydata.org/">pandas</a> and <a href="https://matplotlib.org/">matplotlib </a>libraries, if you do not already have them.</p><h3>Data Analytics Tasks</h3><p>Please perform the following tasks in Python using the <em>violations.csv</em> dataset available from the <a href="https://github.com/nickdcox/learn-nyc-parking-violations">GitHub repo</a>.</p><ol><li>Read the CSV file containing the NYC parking violation data. Change the ‘Issue Date’ column to a date format. Then print out the number of rows imported.</li><li>Perform exploratory data analysis on the imported dataset to identify invalid data. Write code to remove the impacted rows. Then print out the number of rows remaining in the dataset.</li><li>Display a simple plot that shows the number of parking violations issued for each vehicle year.</li><li>List the top 5 violation codes for vehicles that are registered in states other than NY.</li><li>Name the street where Hondas received the most parking violations.</li><li>For vehicles that are from NY only, create a plot displaying the ratio of plate types that are not passenger, month by month.</li><li>Determine whether the color of vehicles with passenger plates receiving the most violations is the same as the color of vehicles with commercial plates receiving the most violations.</li><li>Display the number of registration states represented in the data and the average number of parking violations per registration state.</li><li>Display the plate type that has the most parking violations for each violation code.</li><li>Calculate the percentage of parking violations in each county and display in descending order.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TwZzv-W_lPiTANHO" /><figcaption>Photo by <a href="https://unsplash.com/@nickkarvounis?utm_source=medium&amp;utm_medium=referral">Nick Karvounis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Step 1: Read the CSV file containing the NYC parking violation data. Change the ‘Issue Date’ column to a date format. Then print out the number of rows imported.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9716b9537837dd7d9fa24be62c1112d7/href">https://medium.com/media/9716b9537837dd7d9fa24be62c1112d7/href</a></iframe><pre>Number of Rows: 50000</pre><h4>Code Explanation:</h4><p>We start by making the contents of the pandas module available to our program. pandas is an easy to use open source data analysis and manipulation tool, built on top of the Python programming language. We will use it extensively throughout this project.</p><pre>import pandas as pd</pre><p>We import the contents of the <em>violations.csv</em> file by calling the read_csv() method and store it in a DataFrame, named <em>df</em>. A DataFrame is a two-dimensional data structure with labeled axes, consisting of data, rows and columns. Think of it like a table built in Microsoft Excel or Microsoft Access.</p><pre>df = pd.read_csv(&#39;violations.csv&#39;)</pre><p>We use the print() function to print the string ‘Number of Rows:’ followed by the number of rows in the DataFrame. The argument that we pass to the print() function is made up of two parts. The first is the string ‘Number of Rows: ‘ surrounded in single quotes, denoting it as a string.</p><p>The second part of the argument is calculating the number of rows in <em>df</em>. We use the len() function to tell us the number of rows in <em>df</em>, then wrap it in a call to the str() method to convert the length into a string. Finally, the + concatenates (or joins) the two string parts together. All parts of the argument passed to the print() function must be of type string.</p><pre>print(&#39;Number of Rows: &#39; + str(len(df)))</pre><h3>Step 2: Perform exploratory data analysis on the imported dataset to identify invalid data. Write code to remove the impacted rows. Then print out the number of rows remaining in the dataset.</h3><p>The following data is considered to be invalid:</p><ul><li>Registration State: values that are not a two letter state or province identifier.</li><li>Plate Type: values that are not a three letter identifier (<a href="https://dmv.ny.gov/registration/registration-class-codes">Registration Class Codes</a>)</li><li>Issue Date: dates not within the fiscal year (use 2020–11–30 as the end of the fiscal year)</li><li>Violation Code: codes other than those between 1 and 99 (<a href="https://www1.nyc.gov/site/finance/vehicles/services-violation-codes.page">Violation Codes</a>)</li><li>Vehicle Make: blank values</li><li>Violation Time: blank values</li><li>Vehicle Year: vehicles with dates in the future (use 2020 as the current year)</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff10a9f6534eb8712bb9ccc67667a52d/href">https://medium.com/media/ff10a9f6534eb8712bb9ccc67667a52d/href</a></iframe><pre>Number of Rows: 38937</pre><h4>Code Explanation:</h4><p>We need to subset <em>df</em> to filter out records with invalid data. We are able to apply multiple parameters at once by wrapping each in parentheses and using the &amp; character between them. We use != to represent not equal to, &gt;= to represent greater than or equal to and &lt;= to represent less than or equal to. For the Vehicle Make and Violation Time columns, we need to check for null values by calling the notnull() method.</p><pre>df = df[(df[&#39;Registration State&#39;] != &quot;99&quot;) <br>    &amp; (df[&#39;Plate Type&#39;] != &quot;999&quot;) <br>    &amp; (df[&#39;Issue Date&#39;] &gt;= &#39;2020-04-01&#39;) <br>    &amp; (df[&#39;Issue Date&#39;] &lt;= &#39;2020-11-30&#39;) <br>    &amp; (df[&#39;Violation Code&#39;] != 0) <br>    &amp; (df[&#39;Vehicle Make&#39;].notnull()) <br>    &amp; (df[&#39;Violation Time&#39;].notnull()) <br>    &amp; (df[&#39;Vehicle Year&#39;] != 0) <br>    &amp; (df[&#39;Vehicle Year&#39;] &lt;= 2020)]</pre><p>We use the print() function in exactly the same way as Step 1 above.</p><pre>print(&#39;Number of Rows: &#39; + str(len(df)))</pre><h3>Step 3: Display a simple plot that shows the number of parking violations issued for each vehicle year.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbe47923c2ad0d9ea4afebecd5856dda/href">https://medium.com/media/fbe47923c2ad0d9ea4afebecd5856dda/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*5YtzXKPUSQ_7bRsvUnFxdQ.png" /></figure><h4>Code Explanation:</h4><p>We make the contents of the matplotlib library available to our program. matplotlib is a comprehensive library for creating visualizations in Python.</p><pre>import matplotlib.pyplot as plt</pre><p>We need to create a dataset for the plot, containing vehicle year and the number of parking violations for each those years. To do this, we group the records in <em>df</em> by vehicle year and count the number of parking violations for each year. Each parking violation has a unique summons number.</p><pre>df_vehicle_year = df.groupby(&#39;Vehicle Year&#39;)[&#39;Summons Number&#39;].count()</pre><p>We use the plot() function of matplotlib to create the plot. As an argument, we simply pass the new dataset that we created. Then we use the show() function to display the plot.</p><pre>plt.plot(df_vehicle_year)<br>plt.show()</pre><h3>Step 4: List the top 5 violation codes for vehicles that are registered in states other than NY.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e99cc88749d087747914a5fe526d48f/href">https://medium.com/media/7e99cc88749d087747914a5fe526d48f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*JjGusfN-EcK9B5NIVEVT_Q.png" /></figure><h4>Code Explanation:</h4><p>There are a lot of elements in this single line of code to unpack, so we will take it one step at a time. Take your time to understand this line, as we will use this structure many more times in the steps to follow.</p><p>In the first part of the statement, we filter <em>df</em> to those records with a registration state other than NY.</p><pre>df[df[&#39;Registration State&#39;] != &#39;NY&#39;]</pre><p>Next we group the resulting records by violation code and count the number of parking violations for each violation code.</p><pre>.groupby(&#39;Violation Code&#39;)[&#39;Summons Number&#39;].count()</pre><p>We display the violation codes with the 5 highest counts by using the nlargest() method and passing it the argument 5. The first n rows with the largest values in the count column, in descending order, are displayed.</p><pre>.nlargest(5)</pre><p>Finally, we use the reset_index() method to reset the DataFrame index to the original one. We use it here to present the results in a more elegant manner. We pass the name argument of ‘Count’ to name the column containing the count values.</p><pre>.reset_index(name=&#39;Count&#39;)</pre><h3>Step 5: Name the street where Hondas received the most parking violations.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f286232d1db94dc261eec657158c3d78/href">https://medium.com/media/f286232d1db94dc261eec657158c3d78/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*Vb9JlE6Ry7U1-8ESAhz0VQ.png" /></figure><h4>Code Explanation:</h4><p>This line of code closely follows the structure of what we used in Step 4 above. In this instance we filter <em>df</em> to only those records with a vehicle make of Honda, group the resulting records by street name, count the number of parking violations for each street and display only the street with the most parking violations.</p><pre>df[df[&#39;Vehicle Make&#39;] == &#39;HONDA&#39;].groupby(&#39;Street Name&#39;)[&#39;Summons Number&#39;].count().nlargest(1).reset_index(name=&#39;Count&#39;)</pre><h3>Step 6: For vehicles that are from NY only, create a plot displaying the ratio of plate types that are not passenger, month by month.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d4fa7d6849fe735635ada637212b7b3/href">https://medium.com/media/3d4fa7d6849fe735635ada637212b7b3/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*lpi9Jj_7NGymsYjPboRSDQ.png" /></figure><h4>Code Explanation:</h4><p>We subset <em>df</em> by selecting only those records with a registration state of NY and store it as <em>df_ny</em>.</p><pre>df_ny = df[df[&#39;Registration State&#39;] == &#39;NY&#39;]</pre><p>To calculate the requested ratios, we need to create a dataset to represent the numerator (number of parking violations for all non-passenger vehicles by vehicle year) and another to represent the denominator (number of parking violations for all vehicles by vehicle year).</p><p>For the numerator we filter <em>df_ny</em> to only those records with a plate type not equal to passenger, group the resulting records by vehicle year and count the number of parking violations for each year. We store this as <em>df_ny_notpas</em>.</p><pre>df_ny_notpas = df_ny[df_ny[&#39;Plate Type&#39;] != &#39;PAS&#39;].groupby(&#39;Vehicle Year&#39;)[&#39;Summons Number&#39;].count()</pre><p>For the denominator we don’t need to filter <em>df_ny</em> as we need all records. Instead we just group the records by vehicle year and count the number of parking violations for each year. We store this as <em>df_ny_all</em>.</p><pre>df_ny_all = df_ny.groupby(&#39;Vehicle Year&#39;)[&#39;Summons Number&#39;].count()</pre><p>To calculate the ratios for each year, we simply divide the numerator by the denominator. This is part of the magic of pandas, where it applies the division function to each of the count pairs in the DataFrames, year by year. When a vehicle year appears in only one of the DataFrames, the result is NaN.</p><pre>ratio = df_ny_notpas / df_ny_all</pre><p>We are unable to plot NaN values, so we replace them with 0 using the fillna() method on the <em>ratio</em> Dataframe. The inplace=True parameter updates the values directly in <em>ratio</em>.</p><pre>ratio.fillna(0, inplace = True)</pre><p>We use the plot() function of matplotlib to create the plot. As an argument, we simply pass the new dataset that we created. Then we use the show() function to display the plot.</p><pre>plt.plot(ratio)<br>plt.show()</pre><h3>Step 7: Determine whether the color of vehicles with passenger plates receiving the most violations is the same as the color of vehicles with commercial plates receiving the most violations.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71a8a2e85452b2291d49ef22db40c40f/href">https://medium.com/media/71a8a2e85452b2291d49ef22db40c40f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*R4LSDv5Txn1oFTTQgCcFug.png" /></figure><h4>Code Explanation:</h4><p>We filter <em>df</em> to only those records with a plate type of passenger, group the resulting records by vehicle color, count the number of parking violations for each color and display the color with the most parking violations using nlargest().</p><pre>df[df[&#39;Plate Type&#39;] == &#39;PAS&#39;].groupby(&#39;Vehicle Color&#39;)[&#39;Summons Number&#39;].count().nlargest(1).reset_index(name=&#39;Count&#39;)</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a34f22d8f985097938d5d09258992ec/href">https://medium.com/media/2a34f22d8f985097938d5d09258992ec/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*PuzERCDPRuJZAR98lxfWFg.png" /></figure><h4>Code Explanation:</h4><p>We filter <em>df</em> to only those records with a plate type of commercial, group the resulting records by vehicle color, count the number of parking violations for each color and display the color with the most parking violations using nlargest().</p><pre>df[df[&#39;Plate Type&#39;] == &#39;COM&#39;].groupby(&#39;Vehicle Color&#39;)[&#39;Summons Number&#39;].count().nlargest(1).reset_index(name=&#39;Count&#39;)</pre><h3>Step 8: Display the number of registration states represented in the data and the average number of parking violations per registration state.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b03c6e96f0b69f5adecce3449e4c7e2d/href">https://medium.com/media/b03c6e96f0b69f5adecce3449e4c7e2d/href</a></iframe><pre>Number of Registration States: 45<br>Average Number of Parking Violations per Registration State: 865.2666666666667</pre><h4>Code Explanation:</h4><p>We print the string ‘Number of Registration States’ concatenated with the count of registration states in <em>df</em>. To determine the number of registration states we call the nunique() method on the registration state column in <em>df</em>, which returns the count of distinct observations, i.e., the number of unique states listed in the column. As we did before, we use str() to convert the numeric value into a string.</p><pre>print(&#39;Number of Registration States: &#39; + str(df[&#39;Registration State&#39;].nunique()))</pre><p>We print the string ‘Average Number of Parking Violations per Registration State’ concatenated with the average number of parking violations. To calculate the latter, we group the rows in <em>df</em> by registration state, count the number of parking violations for each state and then average the counts by calling the mean() method.</p><pre>print(&#39;Average Number of Parking Violations per Registration State: &#39; +  str(df.groupby(&#39;Registration State&#39;)[&#39;Summons Number&#39;].count().mean()))</pre><h3>Step 9: Display the plate type that has the most parking violations for each violation code.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73886c1f886e9cd01682b17892967bb7/href">https://medium.com/media/73886c1f886e9cd01682b17892967bb7/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*Xq7tXTTP4aXufGrthEFhDA.png" /></figure><h4>Code Explanation:</h4><p>In this step, we are using more advanced functionality. We will break this code down into snippets to explain.</p><p>We start by grouping the records in <em>df</em> by violation code.</p><pre>df.groupby(&#39;Violation Code&#39;)[&#39;Plate Type&#39;]</pre><p>Next, we want to determine which plate type gets the most parking violations for each of the violation codes. To do this we need to apply a function along an axis of the grouped data. Because we do not specify the axis, it defaults to 0, which is the index.</p><p>The lambda function calls the value_counts() method on each group (violation code) and counts the number of instances of each plate type per group, in descending order. The call to the head() method then gives us the top plate type for each violation code group.</p><pre>.apply(lambda x: x.value_counts().head(1))</pre><p>We use the reset_index() method to reset the DataFrame index to the original one. We use it here to present the results in a more elegant manner. We pass the name argument of ‘Count’ to name the column containing the count values.</p><pre>.reset_index(name=&#39;Count&#39;)</pre><p>Finally, we call the rename() method to rename the level_1 column as Plate Type, to make the output more readable.</p><pre>.rename(columns={&#39;level_1&#39;: &#39;Plate Type&#39;})</pre><h3>Step 10: Calculate the percentage of parking violations in each county and display in descending order.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fe6cccb4340093a52e9eb882f5c62c0/href">https://medium.com/media/6fe6cccb4340093a52e9eb882f5c62c0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*C1-YtHHkTh4-fcF8_eoeyQ.png" /></figure><h4>Code Explanation:</h4><p>We group the rows in <em>df</em> by violation county, count the number of parking violations for each violation county and then store it as <em>df_county</em>. We call the reset_index() method to reset the index and to rename the result column as Percentage.</p><pre>df_county = df.groupby(&#39;Violation County&#39;)[&#39;Summons Number&#39;].count().reset_index(name=&#39;Percentage&#39;)</pre><p>We replace the previously calculated values in the Percentage column by dividing them by the total sum of violations to calculate a percentage for each.</p><pre>df_county[&#39;Percentage&#39;] = df_county[&#39;Percentage&#39;] / df_county[&#39;Percentage&#39;].sum() * 100</pre><p>Finally, we call the sort_values method on <em>df_county</em> to sort the percentages in descending order.</p><pre>df_county.sort_values(by=&#39;Percentage&#39;, ascending=False).reset_index(drop=True)</pre><p>I hope you have found this project a useful way to learn Python data analytics. Please share your feedback in the comments section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1ce1847fa2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/learn-python-data-analytics-by-example-ny-parking-violations-e1ce1847fa2">Learn Python Data Analytics By Example: NY Parking Violations</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>