<?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 Joseph M. Tandiallo on Medium]]></title>
        <description><![CDATA[Stories by Joseph M. Tandiallo on Medium]]></description>
        <link>https://medium.com/@joetandiallo?source=rss-c9a8e383f7f8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-BY37o6EQuzy2UqjYATZBQ.jpeg</url>
            <title>Stories by Joseph M. Tandiallo on Medium</title>
            <link>https://medium.com/@joetandiallo?source=rss-c9a8e383f7f8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 18:05:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joetandiallo/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[Introduction to Web Scraping in Python: Build Your First Scraper]]></title>
            <link>https://medium.com/@joetandiallo/introduction-to-web-scraping-in-python-build-your-first-scraper-fb525167c7d0?source=rss-c9a8e383f7f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb525167c7d0</guid>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Joseph M. Tandiallo]]></dc:creator>
            <pubDate>Tue, 24 Jun 2025 06:15:51 GMT</pubDate>
            <atom:updated>2025-06-24T06:31:19.827Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let’s learn how to build a web scraper using Requests and BeautifulSoup</h4><h3>Introduction</h3><p>Say you want to gather some info from a website, like product details, sports stats, weather, or table data. But since you don’t know how to get it, you’re stuck doing it all by hand, like writing it out one by one or copy/pasting it on your computer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZFmEmFAMufU6CGM4" /><figcaption>Photo by <a href="https://unsplash.com/@sigmund?utm_source=medium&amp;utm_medium=referral">Sigmund</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Well, it may sound simple, but imagine if there are hundreds or thousands of data that you need to copy, and paste it manually. It’s quite a hassle, and you will not get the job done quickly. And if it’s your work, you may have to do this everyday.</p><p>Fortunately, we can do it programmatically using Python with just writing a simple code. Why using Python? Because it has modules that help our web scraping, and it’s customizable to our needs.</p><p>The best thing about using Python is there are endless possibilities, because there are tons of data on the internet that we can collect easily using simple scraper. The data we scrape can also be used for further analysis, whether exploratory analysis, creating visualization, or building a language model from our data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*448RTw2ppJCNUW2L" /><figcaption>Photo by <a href="https://unsplash.com/@goodfacesagency?utm_source=medium&amp;utm_medium=referral">Good Faces</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Building Your Scraper</h3><h4>Part 1: Install Python and all the requirements</h4><p>Make sure you are already installed Python. The first thing you do is create a folder in your computer, and create a new .py file inside the folder. You can do it using IDE such as <a href="https://www.jetbrains.com/pycharm/download/">PyCharm</a> or <a href="https://code.visualstudio.com/download">VSCode</a>.</p><p>Once you’ve done that, open up a terminal and copy-paste this command to install a few libraries to help us pip install requests bs4. This will install two useful tools: <strong>requests</strong> and <strong>beautifulsoup4</strong>.</p><p>There are many tools you can use to scrape websites, but these two are great for starters. They are also very popular and still commonly used when scraping basic or static websites (websites that don’t change content using JavaScript).</p><ul><li><a href="https://requests.readthedocs.io/en/latest/"><strong>requests</strong></a> is used to get the HTML content of a webpage.</li><li><a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/"><strong>beautifulsoup4</strong></a> helps you read and search through the HTML, so you can find the parts you want—like text, links, or table data.</li></ul><p>If you want to understand more about how they work, you can always visit their official documentation online.</p><h4>Part 2: Website to scrape</h4><p>Now let’s find a target website you want to scrape. For starters, I recommend using this website</p><ul><li><a href="https://www.scrapethissite.com/">https://www.scrapethissite.com/</a></li><li><a href="https://www.scrapingcourse.com/">https://www.scrapingcourse.com/</a>.</li></ul><p>These are websites that are intended to be used as web scrapping lesson so it’s safe to try scraping.</p><p>Before we continue, you may want to learn a basic about how websites are build, such as <strong>HTML, CSS, API</strong>, etc. For a simple scraping in static webpage, you just need to know about <strong>HTML </strong>because most of the data is already written in the page, and we can directly pull it out using the tools we installed earlier.</p><p>HTML is made up of tags. These tags tell the browser how to show a website. For example, &lt;h1&gt;Text&lt;/h1&gt; means the text is a heading.<br>Another example is &lt;a href=””&gt;link&lt;/a&gt;, which means it’s a hyperlink. Tags can have attributes that give more information about the tag.<br>For example, the href attribute in the &lt;a&gt; tag shows the URL where the link goes. More information about HTML can be read from this <a href="https://www.freecodecamp.org/news/what-is-html-definition-and-meaning/">explanation</a>.</p><p>in HTML, there’s two important attributes, which are class and ID.<br>A class is used to group similar elements. It helps apply the same style or action to all of them. So if you apply a CSS style to a class, it will applied to all of the attributes inside of that class.</p><pre>&lt;div class=&quot;city&quot;&gt; <br>  &lt;h2&gt;London&lt;/h2&gt; <br>   &lt;p&gt;London is the capital of England.&lt;/p&gt; <br>&lt;/div&gt;</pre><p>This above code creates a section of a webpage about London. It uses a container with the class name &quot;city&quot; to group the content. Inside the container, there&#39;s a heading that says &quot;London&quot; using &lt;h2&gt;, and a paragraph that says &quot;London is the capital of England&quot; using &lt;p&gt;.</p><p>An ID is different. It is used for one unique element. No two elements should have the same ID. For example, the following H1s have unique IDs and can be styled/manipulated uniquely using CSS or JavaScript:</p><pre>&lt;h1 id=&quot;header1&quot;&gt;Hello World!&lt;/h1&gt;<br>&lt;h1 id=&quot;header2&quot;&gt;Lorem Ipsum Dolor&lt;/h1&gt;</pre><h4>Part 3: Inspecting a website</h4><p>To explore further about HTML, you can open the URL above, then <strong>right-click</strong> anywhere on the page and select <strong>“Inspect”</strong> (or <strong>“Inspect Element”</strong> depending on your browser). This will open a new panel — usually on the right or bottom of your screen — called the <strong>Developer Tools</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nBKrL9jq92eifC54M2Zb7g.png" /><figcaption>Right click on a website and select inspect.</figcaption></figure><p>Inside this panel, you’ll see the <strong>HTML code</strong> of the website. It shows everything that makes up the page: the <strong>title</strong>, <strong>text</strong>, <strong>images</strong>, <strong>tables</strong>, <strong>videos</strong>, <strong>links</strong>, and more. This is how the browser builds the page you see.</p><p>If you click the <strong>mouse icon</strong> in the top-left corner of the Developer Tools (usually looks like a square with a cursor), you can <strong>hover over elements</strong> on the page. When you do this, the corresponding HTML will be highlighted in the code. This is useful for learning how websites are structured, in our case, for finding out the HTML of element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*emcZxwFsQmIcSviNMRlwrA.png" /><figcaption>Inspecting an element in a webpage</figcaption></figure><p>In the example above, we can see that the table header <strong>“Category”</strong> is part of a section with the class name product-field, which is inside a bigger table with the class product-list. The <strong>black text</strong> you see in the HTML code is the actual content that appears on the webpage. That’s the part we want to <strong>extract</strong> (or “scrape”) from the website.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*6l_iIai9X5pKnRw18HcmqA.png" /><figcaption>Table Header “Category”</figcaption></figure><p>You can keep using the <strong>Inspect</strong> tool to click on other parts of the page. This helps you find the <strong>class names</strong> or <strong>IDs</strong> of elements like titles, names, prices, buttons, and more — so you’ll know exactly what to target when scraping data.</p><h4>Part 4: Send HTTP Request</h4><p>Open up your IDE, and begin your code by importing the libraries you just installed</p><pre>import requests<br>from bs4 import beautifulsoup</pre><p>We’ll be using this website <a href="https://www.scrapingcourse.com/table-parsing">https://www.scrapingcourse.com/table-parsing</a> to scrape a data from a table, so let’s put that url into a variable</p><pre>url = &quot;https://www.scrapingcourse.com/table-parsing&quot;</pre><p>Next, we are going to access that url by using requests and try to get an information from that request. We’ll be using requests.get() function to return a <strong>response object</strong> from a website which includes the status code, the headers, and the body of the response. Let’s try to get the status code.</p><pre>response = requests.get(url)<br>print(response) # Return the HTML content of the page</pre><p>Try to run that code by default, and it will returned a status message (code) of that website. This tells you whether the request to the website worked or not. You can also write print(response.status_code) if you explicitly want to get the status code. A successful requests will return message <strong>200</strong> or &lt;Response [200]&gt;. Check this information for more about <a href="https://www.w3schools.com/tags/ref_httpmessages.asp">status message</a>.</p><p>When scraping, what you really want is the <strong>HTML content of the page</strong>. That’s where all the text, links, tables, and other data are stored. To get that, simply change the response attribute to .textor response.text. If you run that code now it will returned a bunch of HTML text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fmb-ydJdc9eBfNFntEHOtg.png" /><figcaption>HTML of a website</figcaption></figure><p>This will print out the full HTML of the page — a long text with tags like &lt;div&gt;, &lt;table&gt;, &lt;h1&gt;, and more. This HTML is the <strong>same content</strong> you saw earlier using the <strong>Inspect tool</strong> in your browser. So, it means we’re now able to get the website’s data through Python. To make the code easier to use, let’s wrap it into a function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9f923999bb114b0db2142fbdb369fa5/href">https://medium.com/media/f9f923999bb114b0db2142fbdb369fa5/href</a></iframe><h4>Part 5: Parse HTML</h4><p>Now that we have the HTML, how do we get the information we want — like the table data? The next step is called <strong>parsing</strong> the HTML. This means we’re going to look through the HTML code and pick out the parts we need, like the tags, their attributes, and the content inside them.</p><p>We’ll use <strong>BeautifulSoup</strong> to help with this. It makes the job much easier. In this case, we want to <strong>find and extract all the data from a table</strong>, such as the rows and columns. BeautifulSoup lets us search for the table tag and read its contents step by step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*ZyPrbmGV9bx5UvcON-TEag.png" /><figcaption>The table to be extracted</figcaption></figure><p>Now we are going to inspect all of the cells to know their HTML elements. You can hover over to each cell to find out their element</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*GO7avKPfPX6sHzKxDXrV7w.png" /></figure><p>We found out that each columns is stored in its own HTML class element which are :</p><ul><li>product-id for <strong>Product ID</strong>,</li><li>product-name for <strong>Name</strong>,</li><li>product-category for <strong>Category</strong>,</li><li>product-price for <strong>Price</strong>,</li><li>product-stock for <strong>In Stock</strong>.</li></ul><p>Each of these is placed inside a &lt;td&gt; tag (which stands for table data). Each <strong>row</strong> of the table is inside a &lt;tr&gt; tag (table row), and the rows have a class called product-item.</p><p>Let’s use BeautifulSoup function to parse HTML content</p><pre>soup = BeautifulSoup(html_content, &quot;html.parser&quot;)</pre><p>To get all the data from the table — every cell in every row — we first need to <strong>find the number of rows</strong> in the table. In HTML, a row is marked with the &lt;tr&gt; tag. On this website, there are two kinds of rows:</p><ul><li>Rows with the class <strong>product-field</strong> – this is the <strong>table header</strong> (just the column titles like &quot;Name&quot;, &quot;Price&quot;, etc.)</li><li>Rows with the class <strong>product-item</strong> – this is the <strong>actual data</strong> we want to collect.</li></ul><p>We don’t need the table header, because we can set the column names ourselves later. What we need is only the rows with product-item, because they contain the actual product data. To get all of those rows, we can use the find_all function from BeautifulSoup like this:</p><pre># Find all table rows with the class &quot;product-item&quot;<br>rows = soup.find_all(&quot;tr&quot;, class_=&quot;product-item&quot;)<br>print(&quot;Item found:&quot;, len(rows))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VH_gRF_mkDo-xCy0eUKyNw.png" /></figure><p>The result shows <strong>15 rows</strong>, which means there are 15 products in the table — that’s correct. Now the next step is to go through each of those rows and <strong>get the data from each column</strong>. We will put the column data into a <strong>dictionary</strong>.</p><p>You might wonder, <em>why not use a list?</em> Well, a <strong>dictionary</strong> is better in this case because it clearly tells us what each value is. For example:</p><pre>{ &quot;name&quot;: &quot;T-shirt&quot;,<br>  &quot;price&quot;: &quot;$10.00&quot;<br>}</pre><p>This is much easier to understand than a list like [&quot;T-shirt&quot;, &quot;$10.00&quot;], where you have to remember which position is which column. Also, using a dictionary makes it easier to <strong>maintain your code, add or remove fields later, and convert the data into a DataFrame</strong> for analysis. That’s why we’ll store each row’s data as a dictionary, and then collect all the dictionaries into a list. This list will hold all the product data from the table.</p><pre>class_map = {<br>&quot;product-id&quot;: &quot;ID&quot;,<br>&quot;product-name&quot;: &quot;Name&quot;,<br>&quot;product-category&quot;: &quot;Category&quot;,<br>&quot;product-price&quot;: &quot;Price&quot;,<br>&quot;product-stock&quot;: &quot;Stock&quot;<br>} <br></pre><p>To test our code, we can try to print all of the rows data to show if it can extract all the table data that have &lt;td&gt; tag.</p><pre># Iterate over each table row found<br>for row in rows: <br>    # Find all table data cells within the row<br>    table_data = row.find_all(&quot;td&quot;) <br>    print(&quot;Table Data:&quot;, table_data)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m-vGojssrKTXfnJDshtrUw.png" /><figcaption>Table Data from each rows</figcaption></figure><p>Here it shows all of the table data from each rows. Now it looks messy at first, but don’t worry we’re going to clean those and only get the data we want. The results shows that every “Table Data” have different classes. We will extract the text from every class_map that we defined earlier. Let’s put this code inside the previous row loop.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5787bd466eee97d25de878d3d9dda64/href">https://medium.com/media/e5787bd466eee97d25de878d3d9dda64/href</a></iframe><p>This code will create an empty dictionary called product, then it will extract all the class in each cell that has same class name as our class_map . Then it will put each text from those class_map inside the product. This cell.text.strip() is get only the text and .strip() attribute is to remove any white spaces to make the text cleaner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nBqWpaLM7ct2iNQOxNQoJA.png" /></figure><p>So that’s looking good. We’re able to get the results that we want and our data looks clean. Let’s put the previous code together inside a parsing HTML function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6835fd6270968951765251b169d4fbe/href">https://medium.com/media/f6835fd6270968951765251b169d4fbe/href</a></iframe><p>Don’t forget to create the main function to execute those two function</p><pre>if __name__ == &quot;__main__&quot;:<br>    # Fetch the HTML content from the URL (from return value of get_html)<br>    html = get_html(url) <br>    if html:<br>        read_html(html)</pre><p>and here’s the full code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e1907c0f8221959c9c763dff1b5f41f/href">https://medium.com/media/9e1907c0f8221959c9c763dff1b5f41f/href</a></iframe><h4>Part 6: Optional</h4><p>This is an optional step if you want to store the data into DataFrame, which commonly used to do data analysis by using pandas library. Or maybe you just want to save it as a csv/json. For storing it into DataFrame we will modify the read_html function. This time we will be using list to store our product dictionary and write into DataFrame. Don’t forget to import pandas library at the top.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23357b7c8c032e8ea02108c47e1aa29c/href">https://medium.com/media/23357b7c8c032e8ea02108c47e1aa29c/href</a></iframe><p>Create another function to store it into pandas DataFrame</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/623b7e1880e904af2c6be70e64262366/href">https://medium.com/media/623b7e1880e904af2c6be70e64262366/href</a></iframe><p>Modify the main function to execute the store_to_dataframe function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e5b228c45f188d67d51675798080da5/href">https://medium.com/media/7e5b228c45f188d67d51675798080da5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*vPxVwa-O5hX-ODIJkna__Q.png" /><figcaption>Dataframe</figcaption></figure><p>Now we have successfuly store our data into DataFrame, it looks cleaner and more readable, similar to what we saw on a table. This is a good starting point if you want to take the next step into data analysis. Note that the column header is automatically created because earlier we put our data into dictionaries.</p><h3>Final Thoughts</h3><p>Here it is, we have finished build our first scraper by just using <strong>Requests </strong>and <strong>BeautifulSoup</strong>. It may not looks great but hey, this is a first step for an exciting journey in web scraping world.</p><p>Let’s quickly review what we’ve done in this project:</p><ol><li><strong>Learn the basics of HTML</strong> — We started by understanding how HTML works, especially tags and attributes. This helps us know how website content is structured.</li><li><strong>Choose a target website</strong> — We picked a website we want to scrape. For practice, we used safe sites like <em>scrapethissite.com</em> or <em>scrapingcourse.com</em>.</li><li><strong>Inspect the webpage</strong> — We used the browser’s Inspect tool to look at the HTML and find where the data is located. In this case, we are focusing on a <strong>table</strong>.</li><li><strong>Send a request to the website</strong> — Using the <strong>requests </strong>library, we sent an HTTP request to the site and got the page’s HTML as the response.</li><li><strong>Parse the HTML</strong> — We used <strong>BeautifulSoup </strong>to read and search through the HTML.</li><li><strong>Extract the data</strong> — We found the table rows, then looped through each row and each column to get the data we need.</li><li><strong>Store the data</strong> — We saved the extracted data into a list of dictionaries, so each row becomes an item we can work with easily.</li></ol><p>This is the basic flow of web scraping for static websites. You can test this on a different websites that has tables, for example Wikipedia, which is relatively safe for learning web scraping.</p><p>Thank you for reading. Hope you learned the basic of web scraping.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb525167c7d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploratory Data Analysis Project: Cyclistic Bike-Share Analysis Case Study]]></title>
            <link>https://medium.com/@joetandiallo/exploratory-data-analysis-project-cyclistic-bike-share-analysis-case-study-dedb69807f74?source=rss-c9a8e383f7f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/dedb69807f74</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[geospatial-analytics]]></category>
            <category><![CDATA[data-wrangling]]></category>
            <dc:creator><![CDATA[Joseph M. Tandiallo]]></dc:creator>
            <pubDate>Fri, 19 Apr 2024 08:50:34 GMT</pubDate>
            <atom:updated>2025-06-17T03:43:40.884Z</atom:updated>
            <content:encoded><![CDATA[<h4>Pedaling Through Data: Unveiling Insights with Cyclistic Bike-Share Analysis</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*agYkKvddyHsFObAZ" /><figcaption>Photo by <a href="https://unsplash.com/@real_markjames?utm_source=medium&amp;utm_medium=referral">Mark James Panaligan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>Chicago’s biking scene is getting more and more popular and practical for transportation, all thanks to the city’s work in growing biking infrastructure and encouraging a biking-friendly culture. With lots of bike lanes, trails, and paths all over, biking around the city has become safe and easy. A top favorite is the scenic Lakefront Trail, offering beautiful views of Lake Michigan and drawing in cyclists, runners, and walkers alike.</p><p>This impressive biking setup has also caught the attention of businesses looking to enter the transportation scene. One such example is Cyclistic, a bike-sharing company.</p><h4>About the Company</h4><p>Cyclistic is a bike-sharing company based in Chicago, USA since 2016, offering short-term rentals throughout the city. They have more than 5800 bicycles that are geo-tracked and locked into a network of more than 690 stations across Chicago. Their purpose was to provide a fun, healthy, low-cost transportation option for locals and visitors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/0*Udb72NivtDgfeetj.png" /></figure><p>Cyclistic has implemented flexible pricing plans to appeal to a wider range of consumers, offering options such as single-ride and full-day passes alongside annual memberships. Those who opt for single-ride or full-day passes are referred to as <strong>casual riders</strong>, while those who purchase annual memberships are known as <strong>annual members</strong>.</p><h4>Objective</h4><p>In this scenario, we were given a dataset of bike trip data, then we will determine how annual members differ from casual members regarding bike usage. We will also investigate other areas such as patterns for peak season bike-sharing, ride duration, and ride frequency to determine the most popular bike station.</p><h4><em>Preparation</em></h4><p>The data we used in this case study is historical bike-share trip data from 2023. You can download this data from Kaggle <a href="https://www.kaggle.com/datasets/liamkolanowski/cyclistic-cleaned-data">here</a>. We will use <strong>Python</strong> for data processing, organizing, and cleaning, and visualization.</p><blockquote>Note: Cyclistic is a fictional company, the datasets have a different name. However, the datasets are appropriate for this case study and will answer the business questions. This data has been made publicly available for this case study by Motivate International Inc. under this <a href="https://ride.divvybikes.com/data-license-agreement"><strong>license</strong></a>.</blockquote><h3><strong>Data Processing &amp; Cleaning</strong></h3><p>This process involves finding anomalies in our data, such as missing values, errors, duplicate, or incomplete data. First, we need to download the dataset and save it to our directory, then we will use Pandas as the most popular library for data analyzing. I will use <a href="https://code.visualstudio.com/">Visual Studio Code</a> as my IDE with Jupyter Notebook extension.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0743d0b2f7cc4de489cb057163b755f/href">https://medium.com/media/d0743d0b2f7cc4de489cb057163b755f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xJWvQdyStsnIgaSCc_M-7w.png" /><figcaption>Sample of 20 rows from the dataset</figcaption></figure><p>Then we will check the data types for each column and check the summary of the numerical columns so we can determine our next action.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1315b0e05b355b4f4f158078e98a323/href">https://medium.com/media/d1315b0e05b355b4f4f158078e98a323/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*adYPhJtcUKW1aIkHbvTF6Q.png" /><figcaption>The DataFrame has 17 Columns with 5,677,348 Rows and has 736 MB of size</figcaption></figure><p>These are the descriptions of each column:</p><p>1. Ride_ID: Unique identifier for each bike ride.</p><p>2. Bike_Type: Categorization of the bike used in the ride.</p><p>3. Member_Type: Classification of the rider as an annual member or casual rider.</p><p>4. Start_Station_Name: Name of the station where the ride originated.</p><p>5. End_Station_Name: Name of the station where the ride concluded.</p><p>6. Start_Station_ID: Unique identifier for the starting station.</p><p>7. End_Station_ID: Unique identifier for the ending station.</p><p>8. Start_Latitude: Latitude coordinates of the starting station.</p><p>9. Start_Longitude: Longitude coordinates of the starting station.</p><p>10. End_Latitude: Latitude coordinates of the ending station.</p><p>11. End_Longitude: Longitude coordinates of the ending station.</p><p>12. Season: Seasonal classification of the ride.</p><p>13. Day_Of_Week: Day of the week when the ride occurred.</p><p>14. Started_Datetime: Timestamp indicating when the ride started.</p><p>15. Ended_Datetime: Timestamp indicating when the ride ended.</p><p>16. Ride_Length: Duration of the ride in hh:mm:ss format.</p><p>17. Ride_Length_In_Seconds: Duration of the ride in seconds.</p><pre>df.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*1BmnqfvUqvDjzqRaPVDgJg.png" /><figcaption>Numerical statistic of the DataFrame</figcaption></figure><pre>df.isnull().sum() # Check how many missing values from each columns</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*0F7Oo_xm9MPaSyKMcaVCFQ.png" /><figcaption>The DataFrame doesn’t have any missing values</figcaption></figure><p>As we can see, this dataset is quite huge, with more than 5 million rows. Good thing there are no missing values in this dataset, so we can continue to data cleaning. For this scenario we will:</p><ol><li>Filter the “Unknown” values from End_Latitude,End_Longitude</li><li>Filter entire rows that may have 0 (zero) values in columns Start_Latitude, Start_Longitude, End_Latitude , End_Longitude , as they are not located in Chicago.</li><li>Convert the values from column Ride_Length_In_Seconds into minutes to be more acceptable.</li><li>Assign every column into correct data types.</li><li>Assign every Unknown values from Start_Station_Name and End_Station_Name into Street Names from coordinates values.</li><li>Filter all rows that have ride length under two minutes as they seem too short for bike rides.</li></ol><h4>Filtering The Data</h4><p><strong>Filter all the “Unknown” values.</strong></p><pre>df = df[(df[&#39;End_Latitude&#39;] != &#39;Unknown&#39;) &amp; (df[&#39;End_Longitude&#39;] != &#39;Unknown&#39;)]</pre><p><strong>Filter all zeros from latitude and longitude columns</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6563f864261415c23c27e93c7d448499/href">https://medium.com/media/6563f864261415c23c27e93c7d448499/href</a></iframe><p><strong>Convert seconds to minutes</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93e7e26b08cd6ec7087c8efed2d9a439/href">https://medium.com/media/93e7e26b08cd6ec7087c8efed2d9a439/href</a></iframe><p>After we done those steps, we will look at the info once again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*3jPhx0ZyXr3Ab_NLphP4NQ.png" /><figcaption>DataFrame information</figcaption></figure><h4>Assign The Data Types</h4><p>Let’s proceed to assign every column into correct data types.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fddc25f5ddd0dffd726dc98fa566b69/href">https://medium.com/media/5fddc25f5ddd0dffd726dc98fa566b69/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*8nKjdplXZMiAZ5wNbkKiVw.png" /><figcaption>DataFrame info after assigning into proper data types</figcaption></figure><p>Now that we’ve ensured our data has the correct data types, we’ve also managed to reduce the size of the DataFrame. This is particularly effective when working with large datasets like this one.</p><h4>Data Manipulation</h4><p>Moving forward, our next step is to assign every unknown values from Start_Station_Name and End_Station_Name into Street Names from each start and end coordinates. This process is often called reverse geocoding, which basically converts geographic coordinates into a human-readable address. For this step, we will use a python module <strong>Geopy</strong>. You can read more from the documentation <a href="https://geopy.readthedocs.io/en/stable/">here</a>. We only need Nominatim and GeocoderTimedOut for this process.</p><p>First, we will take a look at the dataframe, which Start_Station_Name and End_Station_Name are Unknown.</p><pre>df[(df[&#39;Start_Station_Name&#39;] == &#39;Unknown&#39;) | (df[&#39;End_Station_Name&#39;] == &#39;Unknown&#39;)]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R6gEMtMa6e_AId5BqXtg9w.png" /><figcaption>All Unknown Start_Station_Name and End_Station_Name</figcaption></figure><p>That’s a lot of unknown values, more than 1 million rows, so it’s better to assign those unknown values into proper street names.</p><p>Let’s begin by grouping by latitudes and longitudes.</p><pre>df_start_station_u = df[(df[&#39;Start_Station_Name&#39;] == &#39;Unknown&#39;)].groupby([&#39;Start_Latitude&#39;,&#39;Start_Longitude&#39;])[&#39;Ride_ID&#39;].count().reset_index()<br>df_end_station_u = df[(df[&#39;End_Station_Name&#39;] == &#39;Unknown&#39;)].groupby([&#39;End_Latitude&#39;,&#39;End_Longitude&#39;])[&#39;Ride_ID&#39;].count().reset_index()</pre><p>Then we will import the modules and create function to extract street names from address</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/065784333bb773664489bf3dad620150/href">https://medium.com/media/065784333bb773664489bf3dad620150/href</a></iframe><p>This function will return street name from each given coordinates. Next, let’s create another function for coordinates from the previous groupby.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6655d8455f4a120bcb60334fca54d2b6/href">https://medium.com/media/6655d8455f4a120bcb60334fca54d2b6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*ESbYA8YRWzujH5h3pouoVA.png" /><figcaption>Start Station</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*hc5ubzQVAD_qFiUCQZO6eg.png" /><figcaption>End Station</figcaption></figure><p>As we can see, all the unknown values have become proper street names. Then let’s finalize this step by merging all street names into our main dataframe. We will do it separately for Start_Station_Name first, then End_Station_Name.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3dc5450ebec206aa8e4bceed78a6e4a/href">https://medium.com/media/a3dc5450ebec206aa8e4bceed78a6e4a/href</a></iframe><h4>Filter Ride Length</h4><p>Our final step is applying a final filter to remove all rows with a <strong>Ride_Length</strong> as it may contain outliers. Let’s begin by looking at the numerical description</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*5G98wACqTHLvQKhKsaGxgw.png" /><figcaption>Dataframe numerical description</figcaption></figure><p>We will also filter and eliminate all rows of the dataframe which have less than 2 minutes Ride_Length . This is just for reasonable purpose as it’s unreasonable to have riding time under 2 minutes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe14bbaadc1f57d15c18f145e1dec9fd/href">https://medium.com/media/fe14bbaadc1f57d15c18f145e1dec9fd/href</a></iframe><p>Let’s proceed to remove the outliers by using Z-Score.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1e9db052b8a117c19207f106281576b/href">https://medium.com/media/c1e9db052b8a117c19207f106281576b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*C1wYpXC7aPTn63BmNROxaA.png" /><figcaption>Dataframe information after removing outliers and filtering below 2 minutes</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*QMy2PaT8-zgQrTHX2FJbKA.png" /><figcaption>Numerical Statistic after removing outliers</figcaption></figure><p>Just by removing all extreme outliers and filtering all below 2 minutes of riding time, the size of our dataframe is reduced.</p><p>That’s it. We’ve completed some data cleaning tasks. Just to recap, we removed any incorrect or unknown values and ensured that each column is assigned to its appropriate data type. With these adjustments, our data is now primed for further processing, whether it’s for visualization or other forms of analysis.</p><h4>Adding Distance Column</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wzTGvDi0bYNYz_U3" /><figcaption>Photo by <a href="https://unsplash.com/@siora18?utm_source=medium&amp;utm_medium=referral">Siora Photography</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Before we proceed further, I’d like to make a small addition by creating a “<strong>Ride_Distance</strong>” column, representing the distance of each ride in kilometers. Fortunately, our dataset provides both the start coordinates and the end coordinates, which are essential for calculating the distance between two points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/0*JDRNGCq0pjgnRkd-.png" /><figcaption>Measuring distance between two points.</figcaption></figure><p>To proceed, we’ll use the Haversine Formula to calculate the closest distance between two points on Earth. For detailed explanations about this formula, please refer to the provided <a href="https://www.baeldung.com/cs/haversine-formula">link</a>. To integrate the formula into our code, we’ll start by installing the module. Simply run <strong>pip install haversine</strong>in the command prompt. Once installed, we’ll import the library into our code, utilizing only the <strong>haversine</strong>and <strong>Unit</strong>functions. For further details on the Haversine module, consult the <a href="https://pypi.org/project/haversine/">documentation</a>. This time we will show the Ride_Distance in Kilometers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a044932df8a650f747ddcc634b420446/href">https://medium.com/media/a044932df8a650f747ddcc634b420446/href</a></iframe><p>Now let’s take a look at the DataFrame.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2r0FOEQoacn52OalXY_ReA.png" /><figcaption>DataFrame with Ride_Distance column</figcaption></figure><p><strong>Ride_Distance</strong> column is successfully added into the DataFrame.</p><p>Let’s check <strong>Ride_Distance</strong> if it has zero values.</p><pre>df[df[&#39;Ride_Distance&#39;] == 0]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z6KBUg--NeKXqO8yOKcOHQ.png" /></figure><p>As we observe, there are so many rows of Ride_Distance value of 0. Also, there are some Ride_Distance values that are not reasonable, for example has higher minutes but the distance is short. This occurrence is typically due to trips that return to their starting point and we only assume the distance just by using haversine. To accurately measure the distance traveled, we require two variables: speed and time. Presently, we only possess the time variable in minutes, and the speed variable is absent.</p><p>To move forward, our initial step involves determining the value of speed. We’ll utilize a fundamental formula: speed equals time divided by distance. Fortunately, not all Ride_Distance entries have a value of zero, allowing us to proceed with our calculations. Additionally, we’ll convert the Ride_Length_In_Minutes to hours to derive the speed in kilometers per hour (Kph).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4988f03378166d637bc8d1737f54e757/href">https://medium.com/media/4988f03378166d637bc8d1737f54e757/href</a></iframe><p>Now that we found the speed, let’s find out the median of the speed</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d6a9d7abc4faea9d23ba5c58e742e91/href">https://medium.com/media/4d6a9d7abc4faea9d23ba5c58e742e91/href</a></iframe><p>After executing the code, we discovered that the median speed is 11.12. We’ll utilize this value to calculate the distance. Then we can drop the Hours and Speed columns because in this case we don’t really need them.</p><pre>df.drop(columns=[&#39;Ride_Speed_kph&#39;,&#39;Ride_Length_In_Hours&#39;], inplace=True)<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ivEuKS8fuCOxK4RqCsYkLw.png" /></figure><p>Next thing we are going to do is the same as Ride_Length_In_Minutes which is removing outliers</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3264a6df017f0a6d50694e7954e6a56/href">https://medium.com/media/e3264a6df017f0a6d50694e7954e6a56/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gJhVMOIfs-rB93_HxjtqFA.png" /></figure><p>We have completed our data cleaning and data wrangling process, and our data looks good for further analysis and visualization. We have lost about 8% of the original data from our data cleaning process, which is quite normal and acceptable.</p><h3>Data Analysis and Visualization</h3><p>Let’s proceed to data analysis and visualization process. For visualization, we will be using seaborn and matplotlib module. Let’s begin by import those modules. For this plot, I will try to match the color palette to Cyclistic logo to make this is Cyclistic-themed analysis.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee0a9026384d6901711f88fc30d4781d/href">https://medium.com/media/ee0a9026384d6901711f88fc30d4781d/href</a></iframe><h3>Ride Frequency Analysis</h3><h4>Member Types</h4><p>For the first analysis, we will analyze the distribution of how many trips each member has taken.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9752c95c70fb39d085d23b2da793ce58/href">https://medium.com/media/9752c95c70fb39d085d23b2da793ce58/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*Dn_9dazH_8IzzpS-TXNmLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*yjrVh-b3JyPsKcMQXXvf0A.png" /><figcaption>Member Type</figcaption></figure><ul><li>From this visualization we know that there are more than <strong>5 million trips</strong> taken in 2023.</li><li>The percentage of total trips taken by Annual Member is <strong>64.3%</strong>, or approximately<strong> 3.38 million trips</strong>, and <strong>35.7%</strong> for Casual Member.</li></ul><h4>Types Of Bicycles Used</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HjpOtdvoJ6jyU-TX" /><figcaption>Photo by <a href="https://unsplash.com/@cliquestudios?utm_source=medium&amp;utm_medium=referral">Clique Studios</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>There are three types of bicycles used, classic, electric, and docked. This chart below shows the total trips each user took on different bikes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e95e46997aef6642c632aef26ccc8e23/href">https://medium.com/media/e95e46997aef6642c632aef26ccc8e23/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*UhJm1u3FWRiz30Ejdn9x9A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*pAbr5jbk9OHdx3LYGpd9VQ.png" /></figure><ul><li>Classic Bike and Electric bikes go hand-in-hand as Electric Bikes reign supreme, capturing <strong>51% of all bike trips</strong>, totaling around <strong>2.6 million rides</strong>. Both bikes are favored by Annual Members, representing about <strong>65% of their trips</strong>.</li><li>Docked bikes trail behind as the least popular option, accounting for a mere <strong>1.2% of total trips</strong>, which are only taken by Casual Members.</li></ul><h4>Timeframe Analysis of Trips Taken in 2023</h4><p>With more than <strong>5 million trips </strong>taken in 2023, we will find out the ride activity for both members across timeline. The first step is to initialize the timeframe.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b0554e31d32956e3aa2360e6b72068d/href">https://medium.com/media/1b0554e31d32956e3aa2360e6b72068d/href</a></iframe><p>We will group each timeframe by member type to find how many trips taken by each member across timeframe.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcac4051828439aea24a1e5393937ac7/href">https://medium.com/media/bcac4051828439aea24a1e5393937ac7/href</a></iframe><p>Let’s visualize every timeframe into bar plots</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe5ed6ad7fa8aac887f973d0a079897a/href">https://medium.com/media/fe5ed6ad7fa8aac887f973d0a079897a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Swnpf7ZKlPiXzfr0qDJKA.png" /></figure><ul><li><strong>August </strong>emerges as the busiest month with over <strong>716k trips</strong>, representing <strong>13.6% of the yearly total</strong>. <strong>Annual Members</strong> dominate this period, accounting for <strong>60%</strong> of August trips. <strong>December</strong>, on the other hand, records the lowest activity with just <strong>170k trips</strong>, constituting <strong>3.2% of yearly trips</strong>. Despite this, <strong>Annual Members</strong> remain very active, contributing around <strong>75.5%</strong> of trips. <strong>July</strong> stands out as <strong>Casual Members’</strong> <strong>preferred month</strong>, with over <strong>300k trips</strong>, making up <strong>5.4%</strong> of the yearly total, but they only represent <strong>39.7%</strong> of total trips during July. <strong>January and February </strong>see a significant difference in trips between Annual and Casual Members, with <strong>Annual Members</strong> accounting for about <strong>78%</strong> of that month&#39;s trips.</li><li><strong>Thursdays and Saturdays</strong> emerge as the busiest days, hosting over <strong>1,6m trips</strong> combined, which is approximately <strong>30.5% of the weekly total</strong>. While <strong>Annual Members favor weekdays</strong>, constituting around <strong>49% of the weekly total</strong>, <strong>Casual Members</strong> tend to ride more on <strong>weekends</strong>, making up roughly <strong>12% of weekly trips</strong>. <strong>Tuesdays and Wednesdays</strong> exhibit notable differences in trip patterns between Annual and Casual Members, with <strong>Annual Members</strong> contributing approximately <strong>70% of weekly trips</strong> on each day.</li><li>Peak riding hours are between <strong>16:00 and 18:00</strong>, with the highest activity at <strong>17:00</strong>. About <strong>65%</strong> of trips during this time are by <strong>Annual Members</strong>. Conversely, <strong>minimal activity</strong> is recorded between <strong>3:00 and 4:00</strong>, with only <strong>27k trips.</strong> The highest difference between Annual Members and Casual Members occurs between <strong>5:00 until 8:00</strong>, with over <strong>77%</strong> of trips are by Annual Members.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddd571c1fbf1d70b456d05dfd534794e/href">https://medium.com/media/ddd571c1fbf1d70b456d05dfd534794e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*EvRiw1U9OLcxTpi2CZLBdQ.png" /></figure><ul><li>Both Annual and Casual Members ride <strong>more frequently in summer</strong> and <strong>less in winter</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AvLxCB8eRm506ZqZ" /><figcaption>Photo by <a href="https://unsplash.com/@joshmccausland?utm_source=medium&amp;utm_medium=referral">Josh McCausland</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Comparison of Trips Taken between Annual and Casual Members</h4><p>Let’s compare the trips taken by Annual Members and Casual Members. We’ll break it down hour by hour over the timeframe and create a heatmap to visualize the data better. But first, we need to set up pivot tables for each membership category. These tables will help us analyze the data more effectively.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86f6af26b3b717e0eb7a9be31991397b/href">https://medium.com/media/86f6af26b3b717e0eb7a9be31991397b/href</a></iframe><p>We can now proceed to build our heatmaps. For these, we will put each member side by side so we can know the differences.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/202bc9b958613ba4653662be9ef14c96/href">https://medium.com/media/202bc9b958613ba4653662be9ef14c96/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DYvW1TaF2Vw519c-K6WGHA.png" /></figure><p>The heatmaps up there show that both of the members mostly hit the road between spring and summer, especially cruising from 2 PM to 6 PM. Now, here’s the kicker: Annual Members aren’t big on weekends, unlike Casual Members who clock in quite a few trips between 10 AM and 4 PM on those days.</p><h3>Minutes Spent on Bikes and Ride Distance Analysis</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8QCE4ozFQe2o08su" /><figcaption>Photo by <a href="https://unsplash.com/@cristiang2023?utm_source=medium&amp;utm_medium=referral">Cristian Guillen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>Minutes Spent</strong></h4><p>This step we will find out how many minutes spent on bicycle in a month/week/day, and what month or day that have most and least minutes spent on bikes. We will also analyze the distance of ride on bicycle between each members.</p><p>First, we’ll look at the distribution for minutes and speed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2183ba8a2fe4fc732431eca0cb84afc/href">https://medium.com/media/d2183ba8a2fe4fc732431eca0cb84afc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*wm-TRoIBLml8Sn32f9ysKQ.png" /><figcaption>Distribution of minutes spent and distance on bikes for each month</figcaption></figure><p>Judging by the plot, we already know it’s best to use median rather than mean. So, this time we will analyze using median.</p><p>Now let’s analyze how many minutes and distance accumulated by each member in the timeframe. By grouping each timeframe, we can determine the total minutes and distance as well the median of those two values.</p><pre>df.groupby(&quot;Member_Type&quot;).agg({&#39;Ride_Length_In_Minutes&#39;: [&#39;sum&#39;, &#39;median&#39;],&#39;Ride_Distance&#39;: [&#39;sum&#39;, &#39;median&#39;]})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*svDtA78Aab558DkjqqMqow.png" /></figure><p>Now we know that the Casual Members spent more minutes spent on bikes which the median is about <strong>11.8 minutes</strong>, while casual members median is about <strong>8.8 minutes on bikes</strong>. Casual Members also ride longer which median distance is <strong>1.76 km</strong> and Annual Members only <strong>1.62 km</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffd5220f26bdcd0fae6162f31ae96f12/href">https://medium.com/media/ffd5220f26bdcd0fae6162f31ae96f12/href</a></iframe><p>To have better representation, we will visualize into bar plot for total minutes spent and total distance</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2433ff5817da03154e3d28c1d4ce0ebe/href">https://medium.com/media/2433ff5817da03154e3d28c1d4ce0ebe/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mBDwS_1wRMM6Hq2pe57T1A.png" /></figure><ul><li><strong>June, July, and August</strong> lead as the top three biking months, accumulating over <strong>30 million minutes</strong> and around <strong>4.8 million kilometers</strong>. <strong>Annual Members</strong> contribute approximately <strong>23% of the yearly minutes</strong>, and <strong>21% of the yearly</strong> <strong>distance </strong>during these months. On the flip side, <strong>December, January, and February</strong> rank as the lowest biking months, totaling about <strong>8% of yearly minutes</strong> and <strong>yearly distance</strong>. Among these, <strong>75% of the minutes</strong> and <strong>the distance</strong> are attributed to <strong>Annual Members</strong>.</li><li><strong>Weekends </strong>emerge as the preferred biking time for <strong>Casual Members</strong>, with approximately <strong>51% more minutes</strong> compared to Annual Members. They contribute <strong>18% of yearly minutes on weekends</strong>. Conversely, <strong>Annual Members</strong> spend more time and cover longer distances on weekdays, with approximately <strong>60% more minutes and 67% more distance </strong>than Casual Members.</li><li>Both Casual Members and Annual Members prefer biking between <strong>4 PM and 6 PM</strong>, making up around <strong>28.5% of hourly biking minutes and distance</strong>. Notably, biking activity declines between <strong>midnight and 4 AM</strong> with only <strong>2.8% of hourly minutes and distance</strong>. An evident contrast between the two membership types arises from <strong>5 AM to 8 AM</strong>, where <strong>Annual Members</strong> spend <strong>74% more minutes and cover 78% more distance</strong> than Casual Members.</li><li><strong>Summer </strong>stands out as the season when most members <strong>spend more time and cover longer distances on bikes</strong>, accounting for about <strong>42% of seasonal minutes and distance</strong>. Notably, <strong>Annual Members</strong> consistently <strong>cover longer distances in each season</strong> compared to Casual Members.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0693a3c1d114ccd02bd2b202fe657092/href">https://medium.com/media/0693a3c1d114ccd02bd2b202fe657092/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mLI2wh8DnAhqT_Iajb7rZA.png" /></figure><p>Based on these plots, it’s evident that <strong>Casual Members</strong> exhibit <strong>higher median</strong> values for both <strong>minutes and distance</strong> compared to Annual Members throughout all timeframes. Additionally,<strong> Casual Members</strong> display <strong>greater variance in median values</strong>, whereas <strong>Annual Members</strong> maintain <strong>relatively consistent median values</strong> across all timeframes.</p><h3>Geographical Analysis</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IB0elxs2BoqHhWRg" /><figcaption>Photo by <a href="https://unsplash.com/@arstyy?utm_source=medium&amp;utm_medium=referral">Austin Neill</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Now, let’s proceed to geolocational analysis where we map the busiest start stations and end stations, also routes based on user type.</p><h4>Most Popular Start Stations</h4><p>To find out where is the favorite location for each member to start their rides, we will group by the start stations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/426e448158de6ef4d4da40e86972d4bc/href">https://medium.com/media/426e448158de6ef4d4da40e86972d4bc/href</a></iframe><p>Here are the most popular start stations for each member.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*D2b9XWAti66VGvUn5d55fw.png" /><figcaption>Most Popular Start Stations by Annual Members</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*kvyMwJxXdBdCWPeyeZBWcA.png" /><figcaption>Most Popular Start Stations by Casual Members</figcaption></figure><p>It turns out Annual members mostly start their ride from Clark St &amp; Elm St, followed by Kingsbury St &amp; Kinzie St, then University Ave &amp; 57th St. For Casual Members, most ride starts at Streeter Dr &amp; Grand Ave, then DuSable Lake Shore Dr &amp; Monroe St.</p><p>Now let’s plot the top 10 most popular start stations</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a0f38e29b3ecf00b79cb850783445df/href">https://medium.com/media/1a0f38e29b3ecf00b79cb850783445df/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EADm_vkCGv5nrWgDlijjyw.png" /><figcaption>Top 10 Start Stations</figcaption></figure><p>Now we can plot heatmap. For this step, We will be using a module named Folium, to visualize the data in interactive leaflet map. You can explore more about Folium from the documentation <a href="https://python-visualization.github.io/folium/latest/">here</a>. We will begin by import folium module in Python, and iPython to save our map as HTML and make it interactive map.</p><pre>import folium<br>from folium.plugins import HeatMap<br>from IPython.display import HTML</pre><p>Let’s begin to create heatmap plot for trips taken by Annual Members</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45e889dbfdb578ecb3c3276a1c68a56a/href">https://medium.com/media/45e889dbfdb578ecb3c3276a1c68a56a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*gBqgOFSYgB78Lrntg3q_Dg.png" /><figcaption>Heatmap of Trips Taken at Start Station by Annual Members</figcaption></figure><p>We will do the same for Casual Members</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a66e2fbbe1cc0b9e3b7666085d40e63/href">https://medium.com/media/9a66e2fbbe1cc0b9e3b7666085d40e63/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*cTeJCE_EbP1D_pZeWLvGGw.png" /><figcaption>Heatmap of Trips Taken at Start Station by Casual Members</figcaption></figure><h4>Most Popular Routes</h4><p>Next, we will examine the most popular routes for Annual and Casual Members. We will create 2 variables for routes, one is for normal routes, and the other is for no round trips route.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/666b3aed2e1152f5ba2f8ca5f705846e/href">https://medium.com/media/666b3aed2e1152f5ba2f8ca5f705846e/href</a></iframe><p>To plot the routes for most popular and the longest routes, we need to find only the top value from each group</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0abcb0895c0dc230b629d5f6b74c848e/href">https://medium.com/media/0abcb0895c0dc230b629d5f6b74c848e/href</a></iframe><p>For plotting, we will be using another module called <strong>Open Route Service</strong>. It’s one of the open-source routing service modules for routing, geocoding, and more. It’s a free service (but limited) and built upon OpenStreetMap data and aims to offer routing services for different modes of transportation. And the cool thing is, that you can integrate into folium. You can use similar other modules like googlemaps or gmaps, which provide more features but they don’t grant free API for their services. You can find out more about <a href="https://openrouteservice.org/services/"><strong>Open Route Service </strong>here</a> and obtain their API.</p><p>First thing we will do is install openrouteservice module by using !pip install openrouteservice , then import the module and your API key.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92515a4c29595ce17ed1eb6f50062664/href">https://medium.com/media/92515a4c29595ce17ed1eb6f50062664/href</a></iframe><p>Then we will create functions, each to fetch coordinates, directions, and decode polyline.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/036dd1ef8be287ff733f61dd0e250dc9/href">https://medium.com/media/036dd1ef8be287ff733f61dd0e250dc9/href</a></iframe><p>Let’s continue to create lists to store route coordinates, and then we will iterate each route, grab the directions and decode geometry.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b634234112806f2cb11643a5ceed87e6/href">https://medium.com/media/b634234112806f2cb11643a5ceed87e6/href</a></iframe><blockquote><strong>Please note:</strong> The distance displayed in this plot and analysis is calculated using the Haversine formula and may not accurately represent the true distance. Obtaining the actual distance for this large dataset necessitates the use of a paid API, which entails a lengthy process.</blockquote><p>For the first plot, let’s take a look at the most popular routes for Annual Members.</p><pre>annual_routes.sort_values(&#39;Number of Trips&#39;,ascending=False).head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gU95pnxnxscxQJgfzWHcuQ.png" /><figcaption>Most Popular Routes for Annual Members</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/973f2a2953fa5b7d1bc7432ce18b87e6/href">https://medium.com/media/973f2a2953fa5b7d1bc7432ce18b87e6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*flfJwjQuzLZz6ViFgtE_mQ.png" /><figcaption>Most Popular Route for Annual Members</figcaption></figure><p>Based on the most popular route for Annual Members, it appears that cyclists are frequenting areas around the University of Chicago campus. The routes between Ellis Ave &amp; 60th St and University Ave &amp; 57th St, as well as Ellis Ave &amp; 60th St and Ellis Ave &amp; 55th St, suggest that cyclists may be commuting to and from the university, indicating a high student or faculty presence. Additionally, the route between University Ave &amp; 57th St and Ellis Ave &amp; 60th St indicates movement between campus and surrounding neighborhoods, possibly for recreational or daily activities. These routes highlight the significance of the university environment in influencing biking patterns and transportation choices in the area.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z3JvLmf_TSmOOrLb" /><figcaption>Photo by <a href="https://unsplash.com/@alisaanton?utm_source=medium&amp;utm_medium=referral">Alisa Anton</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Moving forward, let’s do the same for Casual Members.</p><pre>casual_routes.sort_values(&#39;Number of Trips&#39;,ascending=False).head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2gb8vAuJcrQaYgW8T3oMrw.png" /><figcaption>Most Popular Routes for Casual Members</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/405f340e10127406ea06bdeb3f529558/href">https://medium.com/media/405f340e10127406ea06bdeb3f529558/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*ENuFE4zC99jrw2LKwfX-kg.png" /><figcaption>Most Popular Route for Casual Members</figcaption></figure><p>From these Casual Members routes, the data shows cyclists favoring a route along the lakefront in downtown Chicago. They seem to enjoy the scenic views of Lake Michigan and easy access to downtown attractions. The back-and-forth movement between DuSable Lake Shore Dr &amp; Monroe St and Streeter Dr &amp; Grand Ave suggests they like doing loops or round-trip rides along this waterfront area. This route indicates a mix of leisurely biking and exploring the city center.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s3LUfwQt1j_TJpnp" /><figcaption>Photo by <a href="https://unsplash.com/@kevinrajaram?utm_source=medium&amp;utm_medium=referral">Kevin Rajaram</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Next, we will find out which route is the longest by Ride_Distance, and we will only look at the no-round trips routes.</p><pre>annual_nr_routes.sort_values(&#39;Distance&#39;,ascending=False).head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kn-5Lo-mYuiAx0SlnvX_3A.png" /><figcaption>Annual Members routes that has longest distance</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1113b489aa75e375008f71271fbe7a42/href">https://medium.com/media/1113b489aa75e375008f71271fbe7a42/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*raFxavFmye33mo_A5aFa6w.png" /><figcaption>Longest Route by Annual Members</figcaption></figure><p>Let’s continue to analyze and plot the longest route by Casual Members</p><pre>casual_nr_routes.sort_values(&#39;Distance&#39;,ascending=False).head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EC_eGYYgT5_SaBAQqgTfaQ.png" /><figcaption>Casual Members routes that has longest distance</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1d7063ace92fa63810f337d4ed72e8e/href">https://medium.com/media/d1d7063ace92fa63810f337d4ed72e8e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*N0kzHSTS54RCEhzBQqDn5g.png" /><figcaption>Longest Route by Casual Members</figcaption></figure><h3>Conclusion</h3><h4>Recap</h4><p>We have completed all our analysis for the Cyclistic Bike-Share dataset. To summarize, we conducted various data wrangling tasks, including investigation, cleaning, removal of extreme outliers, ensuring correct data types for each column, and adding distance columns using the Haversine formula. Additionally, we analyzed the distributions of member types and bike types, as well as the distribution of trips taken across all timeframes. We also examined the distributions of minutes spent on bikes by each member and the distance covered on bikes. Finally, we conducted a geographical analysis to identify the most popular stations and routes for both members. This dataset can be further utilized for additional analysis, prediction, and modeling using machine learning techniques.</p><h4>Limitations</h4><p>There are some limitations to this analysis due to the dataset being restricted to minutes and distance only, lacking weather, temperature, or humidity data that could influence riding time and distance. Additionally, the dataset does not include the average speed of each trip, preventing the measurement of the actual distance covered on individual trips. However, we made the most of the available data and conducted our analysis based on the information provided.</p><h4>Final Words</h4><p>That concludes our Cyclistic Bike-Share Analysis articles. Thank you for taking the time to read through them. I hope you found them as enjoyable to read as I did to write. The complete Jupyter Notebook code is available for download on my <a href="https://github.com/joetandiallo/Cyclistic-Bike-Share-Analysis">GitHub repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dedb69807f74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploratory Data Analysis (EDA) Using Python]]></title>
            <link>https://medium.com/@joetandiallo/exploratory-data-analysis-eda-using-python-f85938cb1810?source=rss-c9a8e383f7f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f85938cb1810</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pandas]]></category>
            <dc:creator><![CDATA[Joseph M. Tandiallo]]></dc:creator>
            <pubDate>Mon, 22 Jan 2024 02:43:09 GMT</pubDate>
            <atom:updated>2025-06-17T03:42:55.498Z</atom:updated>
            <content:encoded><![CDATA[<h4>Basic Examples about exploratory data analysis and data visualization in Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8JA9dMkq7TuAnl7L" /><figcaption>Photo by <a href="https://unsplash.com/@johnishappysometimes?utm_source=medium&amp;utm_medium=referral">John Schnobrich</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Exploratory data analysis (EDA) is an important step in the data analyzing process to understand the dataset better. By doing EDA, we can understand the main features of the data, the relationships between variables, and the variables that are relevant to our problem. EDA can also help us identify and handle missing or duplicate values, outliers, and errors in the data.</p><p>For this post, we’re using Python to do data analysis because it has many libraries that can help us perform EDA, such as pandas, numpy, matplotlib, and seaborn. Pandas is a library for data manipulation and analysis. Numpy is a library for numerical computing. Matplotlib and seaborn are libraries for data visualization.</p><p>For this project, we will analyze Goodreads Choice Awards Best Books of 2023.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*s8PTj_UYX2LbZpl-.jpg" /></figure><p>You can find this dataset on <a href="https://www.kaggle.com/datasets/brzy56/goodreads-choice-awards-2023-best-books-of-2023">Kaggle</a> to perform the analysis and start practicing.</p><h3>Understanding the data</h3><h4><strong>Import necessary libraries</strong></h4><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)</pre><h4><strong>Load the dataset into pandas dataframe</strong></h4><pre>#The data is written in a CSV file, so we&#39;re going to use Pandas function to read CSV file.<br>df = pd.read_csv(&#39;Good_Reads_Book_Awards_Crawl_2023_12_27_11_14.csv&#39;)<br><br>df.sample(5) #show the samples of the data</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OM0Mx-hOfvZKcVhKeN6ZAw.png" /></figure><p>Then we’re going to remove some unnecessary column from the dataset, this step is optional, but since we’ll not be using those columns, it’s best to remove it to reduce the size of our DataFrame</p><pre>#The Unused columns are source_URL, Book Description, and About the Author<br>df.drop([&#39;source_URL&#39;,&#39;Book Description&#39;,&#39;About the Author&#39;],axis=1, inplace=True)</pre><h4><strong>Checking the DataFrame</strong></h4><p>Now we’ll check the data types for each column and check the summary of the numerical columns so we can determine our next action.</p><pre>df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*3yilGkwxtYoo-VI2DSuBmg.png" /><figcaption>The DataFrame has 12 columns in total, with 299 rows</figcaption></figure><p>From the .info(), the dataset looks good without any missing values. It also gives us some information such as the shape of our dataset (12 number of columns and 299 number of rows) and the data types of each column.</p><pre>df.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*GVOgVyWXYpnAwQIxmm_4ug.png" /><figcaption>Numerical statistic of our DataFrame</figcaption></figure><p>The .describe() method gives us summary statistics for numerical columns in our DataFrame. It shows us the average value, median values standard deviation, minimum, and maximum values of each numerical columns.</p><h4><strong>Downsizing the Int/Float and assign the data types</strong></h4><p>Once we have identified the appearance and numerical composition of our data, we can proceed to determine the subsequent steps in our data analysis. From the .info(), we know the size of our data, which is 28.2 KB and the data types for each column. The.describe() method shows us the statistics of the numerical columns, such as the minimum and maximum value of each column, as well as the average value.</p><p>By this finding, we can see there are still some columns missing, like Number of Ratings and Number of Reviews, which are supposed to be numerical columns. Turns out those columns use comma “,” as the thousand separator. Other columns like Readers Choice Votes don’t have thousand separators as it stored in General Formatting. The reason to don’t write numbers with thousand separator and rather use plain number instead is because it’s the safest option as the number might be identifiers, or some multi digit number for which it wouldn’t be appropriate to separate the digits. So, in order to do that, we need to remove the comma and replace it with blank.</p><pre>numeric_columns = [&#39;Number of Ratings&#39;,&#39;Number of Reviews&#39;]<br><br>#Remove the character comma from those columns and convert to Int32<br>for column in numeric_columns:<br>    df[column] = df[column].replace(&#39;,&#39;, &#39;&#39;, regex=True).astype(&#39;int32&#39;)</pre><p>This method will remove all the commas from those columns. You can leave this part .astype(&#39;int32&#39;) because pandas will automatically assign the data type into int64. The numbers 64 and 32 stand for how much memory or how many bits per row is it going to store these values.</p><p>You can keep it as it is, but in order to make our DataFrame more efficient we’re downcasting those values into lower values, which is int32. If we take a look at the range from each of the numerical columns below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*ngDampSZP6E3S4UnkD-zdA.png" /><figcaption>Numerical Statistic of our latest DataFrame</figcaption></figure><p>It showed the smallest and highest value of each numerical column. Take an example from Readers Choice Votes column, the smallest value is 935 and the highest is 397565.</p><p>By knowing the range of values, we can now determine the bits to store these values. For references:</p><ol><li>Int8 variables can hold values ranging from -128 to 127.</li><li>Int16 variables can hold values ranging from -32,768 to 32,767.</li><li>Int32 variables can hold values ranging from -2,147,483,648 to 2,147,483,647.</li><li>Int64 variables can store values ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.</li></ol><p>The Int32 is the perfect option because it fits the value range. We can still use Int64, but it’s not proper because it uses more memory and makes our DataFrame less efficient.</p><p>For floats, it’s a bit different because it really affects how many decimal places our data can store. Float16 stores 4 decimal digits, Float32 stores 8 decimal digits, and Float64 stores 16 decimal digits. The best option is to use Float16 because we don’t really need to use many decimal digits in our DataFrame, but we still want to keep the values same as the original.</p><p>Now that we know the value range of each column, we will assign each of those columns into the proper data types.</p><p>There are also some columns that store text values. We can assign those columns&#39; data types into string or category. From the <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html">pandas&#39; documentation</a>, the categorical data type is useful if a string variable consisting of only a few different values, for example gender, social class, blood type, country affiliation, etc. By that definition, the Column Readers Choice Category is the best fit to use the categorical data type.</p><pre>#Convert the rest of the columns to correct data types<br>convert_dict = {&#39;Readers Choice Votes&#39;: &#39;int32&#39;,<br>                &#39;Readers Choice Category&#39;: &#39;category&#39;,<br>                &#39;Title&#39;: &#39;string&#39;,<br>                &#39;Author&#39;: &#39;string&#39;,<br>                &#39;Total Avg Rating&#39;: &#39;float16&#39;,<br>                &#39;Number of Pages&#39;: &#39;int16&#39;,<br>                &#39;Edition&#39;: &#39;category&#39;,<br>                &#39;First Published date&#39;: &#39;datetime64[ns]&#39;,<br>                &#39;Kindle Price&#39;: &#39;float16&#39;}<br>df = df.astype(convert_dict)</pre><p>For the column ‘Kindle Version and Price’, we will remove the price as we already have another column ‘Kindle Price’ that store price data</p><pre>#Separate the currency from the text and put it in the new column<br>df[&#39;Kindle Version&#39;] = df[&#39;Kindle Version and Price&#39;].str.extract(&#39;([a-zA-Z ]+)&#39;, expand=False).str.strip()<br><br>#Change the column into correct data type<br>df[&#39;Kindle Version&#39;] = df[&#39;Kindle Version&#39;].astype(&#39;category&#39;)<br><br>#Remove the previous column<br>df = df.drop(&#39;Kindle Version and Price&#39;, axis=1)</pre><p>Now let’s take a look once again at our data frame to see if the data type has been changed:</p><pre>df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*EMRDHvsIMwz0TQy2Qg_FIg.png" /><figcaption>The DataFrame after changing data types and remove some columns</figcaption></figure><pre>df.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aX5CxDdUAwFbpvk0pn1Edg.png" /><figcaption>Numerical Statistic after changing data types</figcaption></figure><pre>df.sample(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L0F8x3xpSUJjIecOq9h2fg.png" /><figcaption>A sample of the data after data types changes</figcaption></figure><p>As we see in the latest results, we can greatly reduce the memory size of our DataFrame by changing the data types and downcasting integers and floats. Please note that <strong>these steps are optional</strong>, but can be very useful if we’re working with a large dataset.</p><h3>Analyzing and Visualizing the Data</h3><h4>Category Distribution</h4><p>The first analysis is to find out the distribution of books across different categories in the dataset. Then we will visualize using seaborn module.</p><pre>cat_counts = df[&#39;Readers Choice Category&#39;].value_counts()<br>print(cat_counts)<br><br>plt.figure(figsize=(12, 6))<br>sns.barplot(x=cat_counts.index, y=cat_counts.values, palette=&#39;Blues_d&#39;)<br>plt.title(&#39;Distribution of Books Across Categories&#39;)<br>plt.xlabel(&#39;Category&#39;)<br>plt.ylabel(&#39;Number of Books&#39;)<br>plt.xticks(rotation=30, ha=&#39;right&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*-fPt-nlYCiFL53CwH7MSlg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GuSo0oFd7-KDIYz2e8uLZQ.png" /></figure><p>Our data is evenly distributed across all categories, with an exception of Debut Novel category that only has 19 books.</p><p>Next we will analyze the distribution of votes, ratings, reviews, pages, and price for each category. We are going to use boxplot for plotting distributions.</p><pre>fig, axes = plt.subplots(3, 2, figsize=(16, 18), sharey=False, sharex=True)<br><br># First plot Distributions of Readers Choice Votes<br>sns.boxplot(data=df, x=&#39;Readers Choice Category&#39;, y=&#39;Readers Choice Votes&#39;, palette=&#39;Set3&#39;, ax=axes[0, 0])<br>axes[0, 0].set_title(&#39;Distribution of Readers Choice Votes for Each Category&#39;)<br>axes[0, 0].set_ylabel(&#39;Votes&#39;)<br><br># Second plot Distribution of Average Ratings<br>sns.boxplot(data=df, x=&#39;Readers Choice Category&#39;, y=&#39;Total Avg Rating&#39;, palette=&#39;Set3&#39;, ax=axes[0, 1])<br>axes[0, 1].set_title(&#39;Distribution of Average Ratings for Each Category&#39;)<br>axes[0, 1].set_ylabel(&#39;Avg Ratings&#39;)<br><br># Third plot Distribution of Number of Ratings<br>sns.boxplot(data=df, x=&#39;Readers Choice Category&#39;, y=&#39;Number of Ratings&#39;, palette=&#39;Set3&#39;, ax=axes[1, 0])<br>axes[1, 0].set_title(&#39;Distribution of Number of Ratings for Each Category&#39;)<br>axes[1, 0].set_ylabel(&#39;Ratings&#39;)<br><br># Fourth plot Distribution of Number of Reviews<br>sns.boxplot(data=df, x=&#39;Readers Choice Category&#39;, y=&#39;Number of Reviews&#39;, palette=&#39;Set3&#39;, ax=axes[1, 1])<br>axes[1, 1].set_title(&#39;Distribution of Number of Reviews for Each Category&#39;)<br>axes[1, 1].set_ylabel(&#39;Reviews&#39;)<br><br># Fifth plot Distribution of Number of Pages<br>sns.boxplot(data=df, x=&#39;Readers Choice Category&#39;, y=&#39;Number of Pages&#39;, palette=&#39;Set3&#39;, ax=axes[2, 0])<br>axes[2, 0].set_title(&#39;Distribution of Number of Pages for Each Category&#39;)<br>axes[2, 0].set_ylabel(&#39;Pages&#39;)<br><br># Sixth plot Distribution of Kindle Price<br>sns.boxplot(data=df, x=&#39;Readers Choice Category&#39;, y=&#39;Kindle Price&#39;, palette=&#39;Set3&#39;, ax=axes[2, 1])<br>axes[2, 1].set_title(&#39;Distribution of Kindle Price ($) for Each Category&#39;)<br>axes[2, 1].set_ylabel(&#39;Kindle Price ($)&#39;)<br><br>for ax in axes[2, :]:<br>    ax.set_xticklabels(ax.get_xticklabels(), rotation=30, ha=&#39;right&#39;)<br>    <br>fig.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F_hR9HTV30OUsz1B01X3OA.png" /><figcaption>Category Distribution</figcaption></figure><p>As you can see, most of the distribution is skewed, with some extreme outliers in some categories, except in average ratings&#39; distribution where the data is normally distributed. The best way to measure central tendency in skewed data is using median because it is less sensitive to extreme values/outliers.</p><h4>Analyzing by Category</h4><p>We’ll now examine by category from votes, ratings, reviews, pages, and price, and find out the Most Popular Category in 2023.</p><pre>#Determine which column we want to aggregate<br>aggregations = {&#39;Readers Choice Votes&#39;: &#39;sum&#39;, <br>                &#39;Total Avg Rating&#39;: &#39;mean&#39;,<br>               &#39;Number of Ratings&#39;: &#39;sum&#39;,<br>               &#39;Number of Reviews&#39;: &#39;sum&#39;,<br>                &#39;Number of Pages&#39;: &#39;median&#39;,<br>                &#39;Kindle Price&#39;: &#39;median&#39;,<br>               }<br><br>#Group by book category<br>category_vote = df.groupby(&#39;Readers Choice Category&#39;).agg(aggregations).sort_values(&#39;Readers Choice Votes&#39;, ascending=False)<br><br># Calculate the percentage of total votes, total ratings, and total reviews for each category<br>total_votes = category_vote[&#39;Readers Choice Votes&#39;].sum()<br>total_ratings = category_vote[&#39;Number of Ratings&#39;].sum()<br>total_reviews = category_vote[&#39;Number of Reviews&#39;].sum()<br>percent_of_total_votes = (category_vote[&#39;Readers Choice Votes&#39;] / total_votes) * 100<br>percent_of_total_ratings = (category_vote[&#39;Number of Ratings&#39;] / total_ratings) * 100<br>percent_of_total_reviews = (category_vote[&#39;Number of Reviews&#39;] / total_reviews) * 100<br><br># Create new DataFrame of Votes, Ratings, and Reviews<br>result_df = pd.DataFrame({<br>    &#39;Votes (sum)&#39;: category_vote[&#39;Readers Choice Votes&#39;], <br>    &#39;% Votes&#39;: percent_of_total_votes, <br>    &#39;Avg Ratings&#39;: category_vote[&#39;Total Avg Rating&#39;].round(2),<br>    &#39;Number of Ratings&#39;: category_vote[&#39;Number of Ratings&#39;],<br>    &#39;% of Total Ratings&#39;: percent_of_total_ratings.round(2),<br>    &#39;Number of Reviews&#39;: category_vote[&#39;Number of Reviews&#39;],<br>    &#39;% of Total Reviews&#39;: percent_of_total_reviews.round(2),<br>    &#39;Median Pages&#39;: category_vote[&#39;Number of Pages&#39;],<br>    &#39;Median Kindle Price&#39;: category_vote[&#39;Kindle Price&#39;].round(2)<br>    })<br><br>#Find the most voted category<br>max_voted_cat = result_df[&#39;Votes (sum)&#39;].idxmax()<br>max_votes = result_df[&#39;Votes (sum)&#39;].max()<br>avg_rat = result_df.loc[max_voted_cat, &#39;Avg Ratings&#39;]<br><br>#Find the most rated category<br>max_rated_cat = result_df[&#39;Number of Ratings&#39;].idxmax()<br>max_rates = result_df[&#39;Number of Ratings&#39;].max()<br>pct_max_rates = result_df[&#39;% of Total Ratings&#39;].max()<br><br>#Find the most reviewed category<br>max_reviewed_cat = result_df[&#39;Number of Reviews&#39;].idxmax()<br>max_reviews = result_df[&#39;Number of Reviews&#39;].max()<br>pct_max_reviews = result_df[&#39;% of Total Reviews&#39;].max()<br><br>#Print the result <br>print(f&quot;The category &#39;{max_voted_cat}&#39; is The Most Voted Category of 2023, with {max_votes:,} votes&quot;)<br>print(f&quot;The category &#39;{max_rated_cat}&#39; is The Most Rated Category of 2023, having an average rating of {format(avg_rat, &#39;.2f&#39;)}, and number of ratings: {max_rates:,}, or {format(pct_max_rates, &#39;.2f&#39;)}% of total ratings&quot;)<br>print(f&quot;The category &#39;{max_reviewed_cat}&#39; is The Most Reviewed Category of 2023, with {max_reviews:,} number of reviews, or {format(pct_max_reviews, &#39;.2f&#39;)}% of total reviews&quot;)<br><br>result_df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NFWT9mDLrC7luY-OEtMySg.png" /><figcaption>The Most Voted, Most Rated, and Most Reviewed Category in 2023</figcaption></figure><p>Next, we are going to plot that data to have a better understanding and visualization.</p><pre>fig, axes = plt.subplots(3, 2, figsize=(16, 18), sharey=False)<br><br># First plot<br>sns.barplot(x=result_df.index, y=result_df[&#39;Votes (sum)&#39;], palette=&#39;Blues_d&#39;, order=result_df.index, ax=axes[0, 0])<br>axes[0, 0].set_title(&#39;Readers Choice Votes for Each Category&#39;)<br>axes[0, 0].set_ylabel(&#39;Votes&#39;)<br>axes[0, 0].set_xticklabels(labels=result_df.index, rotation=30, ha=&#39;right&#39;)<br><br># Second plot<br>result_df_sorted = result_df.sort_values(by=&#39;Avg Ratings&#39;, ascending=False)<br>sns.barplot(x=result_df_sorted.index, y=result_df_sorted[&#39;Avg Ratings&#39;], palette=&#39;Blues_d&#39;, order=result_df_sorted.index, ax=axes[0, 1])<br>axes[0, 1].set_title(&#39;Average Ratings for Each Category&#39;)<br>axes[0, 1].set_ylabel(&#39;Avg Ratings&#39;)<br>axes[0, 1].set_xticklabels(labels=result_df_sorted.index, rotation=30, ha=&#39;right&#39;)<br><br># Third plot<br>result_df_sorted = result_df.sort_values(by=&#39;Number of Ratings&#39;, ascending=False)<br>sns.barplot(x=result_df_sorted.index, y=result_df_sorted[&#39;Number of Ratings&#39;], palette=&#39;Blues_d&#39;, order=result_df_sorted.index, ax=axes[1, 0])<br>axes[1, 0].set_title(&#39;Number of Ratings for Each Category&#39;)<br>axes[1, 0].set_ylabel(&#39;Ratings&#39;)<br>axes[1, 0].set_xticklabels(labels=result_df_sorted.index, rotation=30, ha=&#39;right&#39;)<br><br># Fourth plot<br>result_df_sorted = result_df.sort_values(by=&#39;Number of Reviews&#39;, ascending=False)<br>sns.barplot(x=result_df_sorted.index, y=result_df_sorted[&#39;Number of Reviews&#39;], palette=&#39;Blues_d&#39;, order=result_df_sorted.index, ax=axes[1, 1])<br>axes[1, 1].set_title(&#39;Number of Reviews for Each Category&#39;)<br>axes[1, 1].set_ylabel(&#39;Reviews&#39;)<br>axes[1, 1].set_xticklabels(labels=result_df_sorted.index, rotation=30, ha=&#39;right&#39;)<br><br># Fifth plot<br>result_df_sorted = result_df.sort_values(by=&#39;Median Pages&#39;, ascending=False)<br>sns.barplot(x=result_df_sorted.index, y=result_df_sorted[&#39;Median Pages&#39;], palette=&#39;Blues_d&#39;, order=result_df_sorted.index, ax=axes[2, 0])<br>axes[2, 0].set_title(&#39;Average Pages for Each Category&#39;)<br>axes[2, 0].set_ylabel(&#39;Pages&#39;)<br>axes[2, 0].set_xticklabels(labels=result_df_sorted.index, rotation=30, ha=&#39;right&#39;)<br><br># Sixth plot<br>result_df_sorted = result_df.sort_values(by=&#39;Median Kindle Price&#39;, ascending=False)<br>sns.barplot(x=result_df_sorted.index, y=result_df_sorted[&#39;Median Kindle Price&#39;], palette=&#39;Blues_d&#39;, order=result_df_sorted.index, ax=axes[2, 1])<br>axes[2, 1].set_title(&#39;Average Kindle Price for Each Category&#39;)<br>axes[2, 1].set_ylabel(&#39;Kindle Price ($)&#39;)<br>axes[2, 1].set_xticklabels(labels=result_df_sorted.index, rotation=30, ha=&#39;right&#39;)<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k3Ckr0i8pKujvqxHmgozjA.png" /></figure><p>So, there you go. Despite not having the highest average ratings, <strong>Romance </strong>takes the title as the <strong>Most Popular Book Category in 2023</strong>, surpassing other categories in votes, ratings, and reviews. It beats second place in Ratings and Reviews by twice the number. Meanwhile, <strong>Humor and History &amp; Biography</strong> ranked as the two least popular book categories in 2023.</p><p>The price is very identical in every category, with exceptions of Romance and Romantasy which have the lowest median price of all categories, despite having high numbers of votes, ratings, and reviews.</p><h4><strong>Finding Correlations</strong></h4><p>Now comes the question. Are there any correlations between votes, reviews, rating, or even the number of pages and price? Does having more pages mean the rating is higher? Or does the category with low price mean more reviews and higher ratings? Let’s find out.</p><pre># Assign the columns<br>columns_of_interest = [&#39;Number of Reviews&#39;, &#39;Number of Ratings&#39;, &#39;Number of Pages&#39;, &#39;Total Avg Rating&#39;, &#39;Readers Choice Votes&#39;, &#39;Kindle Price&#39;]<br><br># Calculate the correlation matrix<br>correlation_matrix = df[columns_of_interest].corr()<br><br># Display the correlation matrix<br>plt.figure(figsize=(10, 8))<br>sns.heatmap(correlation_matrix, annot=True, cmap=&#39;coolwarm&#39;, fmt=&quot;.2f&quot;, linewidths=.5)<br>plt.title(&#39;Correlation Matrix&#39;)<br>plt.xticks(rotation=30, ha=&#39;right&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*K16f_bYLcH5MwGFGZGylBQ.png" /><figcaption>Correlation Matrix</figcaption></figure><p>From this matrix, The Readers Choice Votes have high correlations between Number of Reviews and Number of Ratings. Higher reviews and ratings correlate with higher votes. Pages and price don’t have a strong connection between votes, ratings and reviews. That means the price and thickness of the book doesn’t really affect the votes, ratings, and reviews.</p><h4>Analyzing by Books</h4><p>It’s time to find out what book takes the title as the Most Voted Books in 2023.</p><pre>most_voted_books = df[[&#39;Title&#39;, &#39;Readers Choice Category&#39;, &#39;Readers Choice Votes&#39;, &#39;Total Avg Rating&#39;, &#39;Number of Ratings&#39;, &#39;Number of Reviews&#39;, &#39;Number of Pages&#39;]].sort_values(by=[&#39;Readers Choice Votes&#39;, &#39;Number of Ratings&#39;, &#39;Number of Reviews&#39;], ascending=False).head(20)<br><br>plt.figure(figsize=(14, 6))<br>sns.barplot(x=most_voted_books[&#39;Title&#39;], y=most_voted_books[&#39;Readers Choice Votes&#39;], data=most_voted_books, palette=&#39;Blues_d&#39;)<br>plt.title(&#39;Most Voted Books in 2023&#39;)<br>plt.xlabel(&#39;Book Title&#39;)<br>plt.ylabel(&#39;Votes&#39;)<br>plt.xticks(rotation=30, ha=&#39;right&#39;)<br>plt.show()<br><br>most_voted_books</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OBZ8riWXFMp5Ot9WZO2jlg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZc0dW6a1XO0YwmoBwN_mg.png" /></figure><p>So, the winner has been determined.<strong> Fourth Wing </strong>dominates the 2023 Readers Choice Vote as the Most Popular Book, receiving almost twice the votes as second place Yellowface and close to a million ratings. It takes over half of the votes just for the Romantasy category.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5yOaFLBvBTr4Ws9c-JV9Hg.jpeg" /><figcaption>Fourth Wing by Rebecca Yarros</figcaption></figure><p>Now let’s take a look at the winners from every category.</p><pre>max_votes_index = df.groupby(&#39;Readers Choice Category&#39;)[&#39;Readers Choice Votes&#39;].idxmax()<br>titles_with_max_votes = df.loc[max_votes_index, [&#39;Readers Choice Category&#39;, &#39;Title&#39;, &#39;Readers Choice Votes&#39;, &#39;Total Avg Rating&#39;, &#39;Number of Ratings&#39;, &#39;Number of Reviews&#39;, &#39;Number of Pages&#39;]].sort_values(&#39;Readers Choice Votes&#39;, ascending=False)<br>titles_with_max_votes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQ0n9UYlMA4Z9kEQVy4dkA.png" /></figure><p>Next, we are going to analyze by month published by using barplot to find out the number of books released every month in 2023.</p><pre>import calendar<br>df[&#39;First Published date&#39;] = pd.to_datetime(df[&#39;First Published date&#39;])<br><br>#Get only the books from year 2023.<br>books_2023 = df[df[&#39;First Published date&#39;].dt.year == 2023]<br><br>#Count how many books released every month<br>books_per_month = books_2023.groupby(books_2023[&#39;First Published date&#39;].dt.month)[&#39;Title&#39;].count().reset_index()<br>books_per_month_2[&#39;Month&#39;] = books_per_month[&#39;First Published date&#39;].apply(lambda x: calendar.month_abbr[x])<br><br>plt.figure(figsize=(14, 8))<br>sns.barplot(data=books_per_month_2, x=&#39;Month&#39;, y=&#39;Title&#39;, palette=&#39;Blues_d&#39;)<br>plt.title(&#39;Distribution of Books Published by Date in 2023&#39;)<br>plt.xlabel(&#39;Month&#39;)<br>plt.ylabel(&#39;Number of Books Published&#39;)<br>plt.show()<br><br>books_per_month[[&#39;Month&#39;,&#39;Title&#39;]]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5hnl_cdC4Ry10K_Acs3yyQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/129/1*Cs13fbl-GRx09rHTlPE2lA.png" /><figcaption>Number of books released every month in 2023</figcaption></figure><p>From this plot, we found out that November has the least books released, while September and January are the months that have the most books released.</p><h3>Conclusion</h3><p>From our analysis, we have determined which category is the most and the least popular in 2023. We also did a distribution analysis and correlation analysis between pages, votes, ratings, and review to find out is there any connection between those values.</p><p>What I just showed you is just the tip of how amazingly we can use Python as a tool to do data analysis and visualization. In this article, we have covered the basic and pivotal steps, that provide deeper understanding of the dataset, just by using libraries such as pandas for analysis and matplotlib/seaborn for visualization.</p><p>Thank you for reading my article. I hope you enjoyed reading it and I hope I’ve helped you to understand Exploratory Data Analysis in Python.</p><p>You can find my full code <a href="https://github.com/joetandiallo/Goodreads-Best-Book-of-2023">here</a> on my Github.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f85938cb1810" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Bar-in-Bar Chart in Tableau]]></title>
            <link>https://medium.com/@joetandiallo/create-a-bar-in-bar-chart-in-tableau-27807b606815?source=rss-c9a8e383f7f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/27807b606815</guid>
            <category><![CDATA[tableau]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Joseph M. Tandiallo]]></dc:creator>
            <pubDate>Tue, 28 Nov 2023 05:43:58 GMT</pubDate>
            <atom:updated>2023-11-28T05:43:58.240Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>A bar-in-bar chart is a bar inside another bar. This is useful for making comparisons between two measures (e.g., last year&#39;s sales vs. this year’s sales) or two discrete dimensions (e.g., male vs. female, discount used).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dXS8ckGITxYQ-omJkFMGVw.png" /><figcaption>Example of bar-in-bar chart. Orange is the total of item purchased per category using discount code.</figcaption></figure><p>Before creating a bar-in-bar chart, we need to clean and organize our data so it can be shown properly on the chart. In this example I will use this dataset below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*h1A2c1xJxFqSti8AVqoNbA.png" /><figcaption>Part of the dataset</figcaption></figure><p>From that dataset, we’re going to compare how many items purchased using discount code per category. You can find the full dataset <a href="https://www.kaggle.com/datasets/iamsouravbanerjee/customer-shopping-trends-dataset">here</a>.</p><h3>Create bar-in-bar chart.</h3><p>First, we need to “convert” the Discount Applied column from text to number so it can be counted. To do this, we’re going to create a calculated field from the Discount Applied column. Let’s say if the Discount Applied is “Yes”, it’s going to be counted as 1, using this formula below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*M1U6V-u8Gz4tEfgK8VMvWg.png" /><figcaption>Create a calculated field of Discount Applied</figcaption></figure><p>In the following example, I will use the Item Purchased column to calculate the total of items purchased, because each row in that column is not empty. You can use any column that you like that can be used to count the number of items purchased (e.g., Customer ID), as long as it doesn’t have empty cells.</p><h4>Building the chart.</h4><ol><li>Drag the <strong>Item Purchased</strong> field to the <strong>Column</strong> Shelf and change it to <strong>Measure (Count).</strong></li><li>Drag the <strong>calculated field of Discount Code Applied</strong> we just created and change it to <strong>continuous</strong>. Place it next to <strong>Item Purchased.</strong> Right click on it and choose Dual Axis.</li><li>Drag the <strong>Category</strong> field to the <strong>Rows</strong> Shelf.</li><li>Right click on the top axis, and select <strong>Synchronize Axis.</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*o18hLuXJbKmdQqhVOCl9Dw.png" /><figcaption>Right Click on Discount Code Applied field and choose Dual Axis</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*rLfZjie4nxcm1IvfJskXEg.png" /><figcaption>Synchronize the top axis with the bottom axis</figcaption></figure><p>If your chart changes from bars to something different, you need to select <strong>Bar</strong> under the marks card for both charts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*EHxDlPJtUvEfruOlpCBzRQ.png" /><figcaption>Select the Bar chart under the marks card.</figcaption></figure><p>The final step is to change the size of each chart. We can change the bar of the first chart to be thicker/bigger or the bar of the second chart to be thinner/smaller. For this example, let’s change the bar of the second chart to be thinner.</p><p>Go to the Bar of the second chart marks card and drag the slider from the <strong>Size </strong>tab to the left to make it thinner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*neKtwuuLNBjYB5gpQ4vozA.png" /><figcaption>Change the size of the second bar chart using the Size tab under marks card.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*5NcUur6rTI9WhxMLxKZetw.png" /><figcaption>The final result after resizing the second bar chart.</figcaption></figure><h4>Additional Steps</h4><p>After creating the bar-in-bar chart, you can now format the chart to make it more visually appealing. For example, try changing the label color of the second bar chart, or hiding the top axis so it will not confuse people. Don’t forget to provide additional information on the tooltip. For these additional steps, I leave it to your preferences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*iS135L_wMn-i-S_mta4KKw.png" /><figcaption>Formatting the chart to make it more appealing.</figcaption></figure><h4>Conclusion</h4><p>Bar-in-Bar chart is one of the many ways to display a comparison of two different measures in one chart, making it easier to see without having to switch between charts.</p><p>This practice is one of many ways to create bar-in-bar chart in Tableau and can be applied to many cases like comparing sales vs. profit, actual vs. forecast, or sales between two timelines for different products.</p><p>I hope this article was helpful to you. Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27807b606815" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>