<?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 Sean Holland on Medium]]></title>
        <description><![CDATA[Stories by Sean Holland on Medium]]></description>
        <link>https://medium.com/@seanlukeholland?source=rss-f5efeadb387a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZRj5Hc8OgW7HZoZQl4gKhA.jpeg</url>
            <title>Stories by Sean Holland on Medium</title>
            <link>https://medium.com/@seanlukeholland?source=rss-f5efeadb387a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:22:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@seanlukeholland/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The SQL Looked Right. The Number Wasn’t.]]></title>
            <link>https://medium.com/@seanlukeholland/the-sql-looked-right-the-number-wasnt-06f92cbd6ec2?source=rss-f5efeadb387a------2</link>
            <guid isPermaLink="false">https://medium.com/p/06f92cbd6ec2</guid>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[analytics-engineering]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Sean Holland]]></dc:creator>
            <pubDate>Tue, 06 Oct 2026 19:27:55 GMT</pubDate>
            <atom:updated>2026-10-06T19:27:55.752Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Four decisions from building a SaaS retention model in dbt, and why they matter more once AI is writing the queries</em></p><p>I used Claude to help build a SaaS revenue retention model in dbt on synthetic CRM data. The AI wrote most of the SQL fast. The four decisions that made the numbers trustworthy were mine. I codified these changes into a semantic layer:</p><ol><li><strong>Check the output against what you know is true.</strong> The retention model reported 100% revenue retention for a cohort that had lost two of its five customers. Found when sanity-checking.</li><li><strong>Define “complete” once.</strong> Unfinished periods made recent retention look like it had collapsed — discovered using visual exploratory data analysis.</li><li><strong>Quarantine bad rows.</strong> AI’s testing decision was too conservative and would have made crucial reports unavailable for users.</li><li><strong>Retire an old metric methodically.</strong> Give the old version an awkward name and an end date. Communicate, ticket and tag documentation.</li></ol><p>AI can write the SQL. It can’t decide what your numbers mean. Those decisions, written down where an AI will look, are the semantic foundation that makes LLM-derived insights trustworthy.</p><p>If AI is commoditizing code-writing then we humans should get to answers that drive business decisions faster, right?</p><p><a href="https://www.instagram.com/p/DblaIjLsIBP/?hl=en">Yes, but…</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*MkoHUo6mw7JWVaC-F6ugpg.png" /><figcaption>Instagram — @gudim_public</figcaption></figure><p>AI drafts the query in seconds. Making the answer trustworthy still takes human work.</p><p>The project: a synthetic, Salesforce-shaped CRM dataset (six tables, about 14,000 rows) modeled in dbt on DuckDB, with Databricks as a second target for dashboards and exploration. The business question: how is net revenue retention trending, and what’s the most meaningful way to group it?</p><h3>1. The AI-generated model said one cohort kept 100% of its starting revenue.</h3><h4><strong>On inspection, the actual retention was 75%.</strong></h4><p>There’s no substitute for a human checking output against what they know.<strong> </strong>The model said one cohort kept 100% of its starting revenue, but that cohort had lost two of its five customers and actually kept 75% of its revenue. Not 60% — read on.</p><p>Gross revenue retention (GRR) measures how much of a cohort’s starting revenue you kept, ignoring upsell. Before building anything on top of the model, I read the first monthly cohort term by term. Its GRR went 100% → 77.5% → 85% → 100%. Retention that recovers after customers leave was the tell.</p><p>The cause was one line. The SQL capped revenue for the whole cohort, least(sum(mrr), starting_mrr), when it needed to cap each account first and then add them up. Capped at the cohort level, one customer&#39;s upgrade hid another customer&#39;s churn. Moving the cap to the account level gave the correct 100% → 77.5% → 75% → 75% GRR.</p><p>Two lessons:</p><ul><li><strong>The wrong version was confident and plausible.</strong> No code review caught it. A person reading four rows of output with an expectation in mind did. That’s the failure mode I’d worry about most with AI-written metrics: not code that breaks but code that returns a believable wrong answer.</li><li><strong>The obvious test doesn’t catch it.</strong> “GRR can never exceed NRR” sounds right, but the broken formula passes it by design. The test that works checks that retained revenue never exceeds the starting revenue of the accounts still in the cohort.</li></ul><h3>2. The AI-generated data showed NRR underperformance in the most recent period.</h3><p>I created a heatmap visual and immediately noticed the underperformance concentrated in the most recent period of every annual cohort.</p><blockquote><strong>Recent periods weren’t underperforming. They just weren’t finished.</strong></blockquote><p>Define “complete” once, in the model, so every report and every AI query uses the same rule.</p><p>The right side of the heatmap was full of red. That could pass for normal churn, but one habit I learned early is to look at data at least two ways and to gut-check percentages against real dollars.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*WW0msn3dBq1mK8No37fILw.png" /><figcaption><em>Did NRR really drop more than 50% in the most recent term?</em></figcaption></figure><p>The fix: a small macro, is_period_complete, compares each term&#39;s end date to one as_of_date variable. A flag on the segment mart marks whether every account in a cell has finished that term. Trend analysis uses complete cells only. Incomplete cells stay visible but labeled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*gWsgw0IwF9cUCOx7Xt1v1Q.png" /><figcaption>Red on the right is normal, but not TOO red.</figcaption></figure><p>What matters most is where the rule lives. In a previous role, partial periods were handled with one-off logic in individual queries, each slightly different. Part of a data governance effort I led there moved that flag into a base table so every report used one definition. Defined once, it’s a rule. Defined per query, it’s a dozen rules that mostly agree and hours spent reconciling them before every presentation.</p><p>AI is supposed to <strong><em>save </em></strong>time.</p><h3>3. AI-defined testing “decided” the optimal test setting for bad rows should be ERROR</h3><p><strong>I assessed that this approach would immediately invite a barrage of emails and DMs from report-users. </strong>Bad rows shouldn’t stop the pipeline — nor should they slip through it. So I added an interim model to route bad rows to a quarantine table with a reason attached.</p><blockquote>Good data keeps flowing — bad data stays visible.</blockquote><p>I made the synthetic data dirty on purpose: null lead sources, duplicate emails, inconsistent casing and opportunities closed before they were created. Tests on clean data only prove you can write tests. Tests on data with known defects show what the tests are for.</p><p>Since the test checking that <em>close dates come after created dates</em> was set to error, dbt skipped the funnel model and three of its tests when it failed. <strong>This makes report-users mad.</strong></p><p>Switching it to warn would let nine bad opportunities flow into funnel metrics, where nobody downstream would see them. <strong>This also makes report-users mad.</strong></p><p>So I split the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*77GdUmcZbE1apgFqBhnCTw.gif" /><figcaption>Valid rows follow green path, invalid are quarantined (red)</figcaption></figure><p>A base model holds every opportunity. Valid rows go to staging, where the rest of the project reads them. Invalid rows go to a rejected model with the reason attached. A reconciliation test confirms every row lands in exactly one place, and the close-date test now guards the filter itself, which makes error the right severity again. Once the source is fixed, the rows pass on the next run and the rejected table empties on its own.</p><p>It still needs an owner — a rejected table nobody reviews is just a slower way to lose data. <em>But this trade-off requires human judgment.</em></p><h3>4. Retiring the old GRR</h3><p><strong>When you fix a metric, the old number is already in someone’s deck. I renamed the old version so nobody reuses it by accident, keeping it out of downstream reports and set an end date.</strong></p><p>When explaining the change to leadership, skip the logic and lead with the business impact. For example: the old GRR made customer retention look several points better than it was.</p><p>In the model, the corrected calculation took the name gross_revenue_retention_pct. The old logic kept a deliberately awkward name, gross_revenue_retention_cohort_capped_pct, so nobody pastes it into a deck by accident. Its documentation says &quot;do not use for new reporting,&quot; so the warning travels with dbt docs instead of living in a wiki.</p><p>In an organization I’d also park the legacy measure in a clearly labeled BI folder and set a sunset date with notice to report-users. “Keep both” with no end date means forever.</p><p>The SQL change took minutes. Deciding how long to keep the old number and how to tell people about it is the real work.</p><h3>What AI can’t know</h3><p>Here’s what’s important: LLMs don’t actually “know” anything. It’s deceptively easy to lose sight of this, and yet it’s critical we keep this in view when building the tool into our business.</p><p>An AI reading a well-documented model can write good SQL, even complex and elegant SQL, much faster than I can. But it can’t “<em>know</em>” that retention must be capped per account.</p><p>It can’t “<em>know</em>” the last column of a cohort table covers a period that isn’t over, <em>unless a person decided that and wrote it down where the AI will look.</em> In a previous role, I ended up writing that kind of context for an internal LLM tool before I knew the practice even had a name.</p><p>Using an LLM has two costs. One is technical and priced in cents per million tokens. The other is hidden: confident hallucination.</p><blockquote>The hidden cost can easily be orders of magnitude bigger than token cost.</blockquote><p>A good first step to scoping and minimizing that cost: work with an analytics engineer who understands your business.</p><p><em>Sean Holland is based in Cincinnati, OH and focuses on delivering business insights built on semantic foundations that both people and LLMs can use. He has worked in data for over five years and has held technical, financial and client-facing roles for over ten years across real estate, consulting, blockchain and private equity. Connect with him on </em><a href="https://www.linkedin.com/in/sean-holland-89b12621/"><em>LinkedIn</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06f92cbd6ec2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cyclistic Bike Share Part II — Pricing Analysis]]></title>
            <link>https://medium.com/@seanlukeholland/cyclistic-bike-share-part-ii-pricing-analysis-7dcad9d4702b?source=rss-f5efeadb387a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dcad9d4702b</guid>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[roi]]></category>
            <category><![CDATA[pricing-strategy]]></category>
            <category><![CDATA[marketing]]></category>
            <category><![CDATA[cycling]]></category>
            <dc:creator><![CDATA[Sean Holland]]></dc:creator>
            <pubDate>Fri, 05 Apr 2024 15:43:38 GMT</pubDate>
            <atom:updated>2024-04-05T16:10:40.475Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cyclistic Bike Share Part II — Pricing Analysis</h3><p><em>Part I can be found (</em><a href="https://medium.com/@seanlukeholland/cyclistic-bike-share-case-study-8a9d7441bfec"><em>here</em></a><em>) and contains data analysis findings including the target audience used as the basis for the marketing campaign analyzed below.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wqBwzC828kVzBGdErFaDdQ.png" /></figure><p>When we left off, we had recommended a specific target market for the Cyclistic marketing team to target with a new digital marketing campaign.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ijJBhQCHvmloONJN2yM2fA.png" /></figure><p>Based on the data we analyzed, this group was uniquely ripe to be converted to the more profitable “Member” category.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dxPHK-UdR1JpK1MNUTaS2Q.png" /></figure><p>In order to better inform the marketing team on exactly how much to spend, we need to better understand the economics behind Members and Casuals so we can build some scenarios to estimate changes in our margin projections for next year. For this we’ll rely mostly on good old-fashioned Excel.</p><h3>Starting Metrics</h3><p>Based on our previous analysis we have some important information that will inform our model. There are also some additional metrics that may be useful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XsTwuGEiZ2A_cUJ1tgv6Lg.png" /></figure><p><strong>AVERAGE RIDE TIMES</strong></p><ul><li>MEMBERS — 11.63 minutes</li><li>CASUALS — 16.21 minutes</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F9IqV9j28qPTiBut-6G1yQ.png" /><figcaption>Casual rides surging in summer months</figcaption></figure><p>We also know how many rides each cohort takes per month so we can model this annual cyclicality with high confidence moving forward.</p><h3>ASSUMPTIONS — BASE CASE</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DCXaVQkB2mpRx80z-5RV4w.png" /></figure><p>Extrapolating from data <a href="https://www.linkedin.com/pulse/unit-economics-bike-sharing-business-models-north-america-kumar/">here</a> and <a href="https://citibikenyc.com/system-data">here</a> we’ve made the following assumptions:</p><p><strong>MEMBERS</strong></p><ul><li>$.30 revenue per minute</li><li>Avg Operating Margin of 40%</li><li>Avg Margin / Minute of $.12</li><li>Therefore Avg Margin / Ride of $1.40</li></ul><p><strong>CASUALS</strong></p><ul><li>$.36 revenue per minute (20% markup)</li><li>Avg Operating Margin 15%</li><li>Avg Margin / Minute of $.054</li><li>Therefore Avg Margin / Ride of $.88</li></ul><p><strong>MARGIN DIFFERENTIAL — Why Casuals are less Profitable</strong></p><p>Casuals are less predictable than members with respect to treatment of bikes and tend to ride significantly longer than members, both of which contribute to higher variable costs vs Members and a resultant lower Avg Operating Margin. We also know from management that Members are “much more profitable” than Casuals.</p><p>Given these assumptions and a 100% conversion ratio (all 601,955 casuals we’re targeting become members), we get a +4.78% increase in overall margin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*ZwH-vpkORVy93u6AKdr9Xg.png" /></figure><blockquote>Converting all 601,000 “Convertible Casuals” gives us an additional margin of $325,000, a +4.78% YoY change</blockquote><h3>BASE CASE + GROWTH FACTOR</h3><p>Based on the fact that average margin is directly dependent on # rides, a 10% growth rate in # rides results in a 10% increase in year 2 margin. However, because this also increases the available Convertible Casuals by 10% to ~ 660,000, we see a larger delta on the margin increase and the additional +4.78% jumps to +5.24% for a total overall margin increase of 15.24%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*pVHIqOF5ltKRLIO3IwaETg.png" /></figure><p>These are optimistic assumptions though.</p><h3>EFFECTS OF CONVERSION FACTOR AND ATTRITION</h3><p>Predictably if we cut the cut the <em>conversion ratio</em> in half we see the Avg Margin increase cut in half to +2.39%.</p><p><em>Attrition</em> isn’t quite as straight forward since it changes over time and effects Casuals at a significantly higher rate but using a base scenario of 2% for Members (6% for Casuals) we see a ~42% reduction in margin increase to +2.75%</p><h3><strong>ASSUMPTIONS — PUTTING IT ALL TOGETHER</strong></h3><ul><li>50% digital marketing conversion ratio</li><li>2% (starting) attrition loss for Members</li><li>3X member attrition for Casuals therefore starting at 6%</li><li>5% attrition decay monthly as we retain “stickier” riders over time</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*kwjEavkKrcsh2-v1TZGxig.png" /></figure><blockquote>These new assumptions give us an additional $ margin of $705,000 (+10.35% YoY)</blockquote><h3>RECOMMENDATIONS TO MARKETING</h3><p>Leaving the other assumptions aside for a moment and returning to our <strong>base case,</strong> we can glean that these <strong>convertible casuals represent a rough maximum of $325,000 of potential additional margin </strong>in year 2.</p><p>We’ve restricted this analysis to a single year’s projections but it’s fair to say that, given their higher variable costs and correspondent lower margins, spending up to $200,000 now would result in a payback period of roughly a year, after which our margins would likely grow 3–5% depending on growth rate, attrition and digital marketing conversion rates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dcad9d4702b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Win Your Fantasy Football League]]></title>
            <link>https://medium.com/@seanlukeholland/how-to-win-your-fantasy-football-league-54e00e3b48e7?source=rss-f5efeadb387a------2</link>
            <guid isPermaLink="false">https://medium.com/p/54e00e3b48e7</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[fantasy-sports]]></category>
            <category><![CDATA[nfl]]></category>
            <category><![CDATA[fantasy-football]]></category>
            <dc:creator><![CDATA[Sean Holland]]></dc:creator>
            <pubDate>Sun, 24 Mar 2024 17:46:18 GMT</pubDate>
            <atom:updated>2024-05-29T18:53:59.939Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part II of our “In Search of Fantasy Glory“ Series</h4><p>Part I can be found (<a href="https://medium.com/@seanlukeholland/in-search-of-fantasy-glory-part-i-3f217dde772a">here</a>) and details the data engineering ETL process.</p><blockquote>Client: “How do I beat my competition in Fantasy Football?”</blockquote><blockquote>Me: “I don’t know. Let me take a look.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*aEyycej6KHUtsqalEpSKgA.png" /><figcaption>*data analysis / welding noises*</figcaption></figure><blockquote>Me: “I have some thoughts”</blockquote><h3><strong>THE DATA</strong></h3><ul><li>1 league</li><li>6 users (small league)</li><li>4 years</li><li>67 weeks</li><li>197 matchups</li><li>11 active roster spots including 3 flex (to balance small league size)</li><li>3911 unique player performances</li></ul><h3>LEAGUE SPECIFICS — SCORING</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*TwqGGlqC8ti8hwq94pb72A.png" /><figcaption>Half PPR league</figcaption></figure><p><strong>IMPORTANT NOTES AND CAVEATS</strong></p><p><strong>This analysis was based only on ACTIVE player’s fantasy outputs</strong> which means that if a player was riding the bench and had a big (or terrible) game, that data is not included in this data set. This has some implications regarding the analysis.</p><p>First, the data naturally self selects such that injuries should only have an impact on the fantasy output of the game in which they were injured. If it was early in the game, this can have a huge impact on that single performance but that should smooth out on a per game basis as that player would be benched or otherwise inactive until they recovered and were ready to play again. However, <strong>injuries can have a <em>massive </em>impact on the sum total fantasy output of a player on an annual basis. Because of this, it’s generally better to compare avg fantasy output on a per-game basis. </strong>But, at the end of the day, it’s the roster with the higher combined points that wins a week.</p><p>It’s also important to note that <strong>defenses (DEF) have been left out of our analysis</strong> for a couple reasons. Defenses are unique in that they represent the efforts of an entire group of players which is constantly changing due to injuries and coaching schemes so it’s not meaningful to analyze them in the same way we’d analyze players at the other positions. Given this dynamic nature, defenses are constantly being dropped and picked up throughout the season so they can have large contributions to multiple users in a league in a single season. Related to this point, defensive fantasy output is directly proportional to the performance of the offense of the team they are playing against and thus favors picking up defenses that are playing worse NFL offenses. These features make analysis of single defense misleading and hard to attribute to specific user’s success.</p><h3>HOW TO WIN FANTASY FOOTBALL</h3><p>Let’s follow this question backward logically to understand what’s important when analyzing this data. What “lens” should we be using?</p><p>In order to win a fantasy football championship you need to beat the other person in your league that’s made it to the championship who also likely has a dominant net win number defined as (wins — losses). As it turns out, the average number of wins required to win this league happens to be 11 meaning…</p><blockquote>…you need to win about 65% of your games to have a shot at taking the title</blockquote><p>A win is defined as scoring more fantasy points than your opponent on any given week. It does not matter whether it’s a large or a small margin — the win is all that matters.</p><p>In order to score more points than your opponent, the players on your ACTIVE ROSTER (not your bench!) need to score more points than your opponent’s active roster.</p><h4><strong>ACTIVE ROSTER MAKEUP</strong></h4><p>Every Roster has the following positions that need to be filled:</p><ul><li>Quarterback (QB) — 1</li><li>Wide Receiver (WR) — 2</li><li>Running Back (RB) — 2</li><li>Tight End (TE) — 1</li><li>Flex (WR/RB/TE) — 3</li><li>Kicker (K) — 1</li><li>Defense (DEF) — 1*<br>*note we’ve taken Defenses out of our analysis</li></ul><p>The flex positions can be any or all of WR, RB or TE.</p><p>From the data we discovered that the <strong>average fantasy output per game (in points) for each position is as follows:</strong></p><ul><li>QB — 21.4</li><li>WR — 12.9</li><li>TE — 10.1</li><li>RB — 13.7</li><li>K — 7.9</li></ul><p>Given the lower average output from TE’s, <em>the majority of the time the flex positions are going to be WR’s or RB’s</em>. If we split it evenly for argument’s sake, that means RB’s and WR’s would each get 3.5 spots on a roster. More importantly though, RB’s and WR’s are generally seen as substitutes for one another during roster construction and this dynamic does not exist with any of the other positions. Later, we’ll delve deeper into this.</p><h4>“THE S*** TALKING DASHBOARD”</h4><p>So back to the basic question of “how to win at fantasy football”. For this we can start by examining user trends, including what a winning season looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X5RmbkMcMSrZ4QHru2EDOA.png" /></figure><p>The above dashboard has a lot going on — but the overall goal is to show which users are winning more and what their fantasy output looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*Gaw99GhcI1KiYg1A2bnIrQ.png" /><figcaption>League winners circled in BLUE</figcaption></figure><h3>What does a winning season look like?</h3><ul><li>*Avg points to win season — 2296 (137 per game)</li><li>Avg # wins needed to win season — 11</li></ul><p><em>*remember we’ve excluded defenses</em></p><p>Ok this is a starting point! But how do we construct a roster that will maximize fantasy output?</p><h3>What does a winning roster look like?</h3><p>Given our average points per game scored at each position (above), that would mean that each position averages a certain amount of the total team’s fantasy output given as follows (<strong>weighted fantasy contribution</strong>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*aG947E_oU_IAwHuKB4ofyA.png" /></figure><blockquote>Which means that WR’s and RB’s account for 70% of a team’s total fantasy output</blockquote><p><strong>In fact, in this league the <em>combined</em> impact from QB, TE and K are less than the impact from just WR’s or RB’s. </strong>Given their huge contribution to a team’s weekly fantasy output, the choice of which WR’s and RB’s to use seems like a critical leverage point and heavily influences a team’s chance of winning or losing. We’ve also noted that WR’s and RB’s are substitutes for each other and we’ve noted that on average, an RB scores .8 more fantasy points than a WR on any given week.</p><blockquote><strong>So does more RB’s = more wins?</strong></blockquote><p>Let’s take a look at the winners again from a different angle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xSP5SUGm9rpgVEm6UoH7FQ.png" /></figure><p>The top row shows user’s RB usage and the bottom row shows user’s WR usage for each of the last four years. From this we found the following:</p><blockquote>League winners used Running Backs more than Wide Receivers</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*iHdAlFSv9bUXQVyWk14KKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*XsqWh5q8LiRdD4T5qtX_Qg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*CGm10uwO4u-YRryC4nEhqQ.png" /><figcaption>Note the trends are almost mirror images indicating WR’s and RB’s are substitutes for each other</figcaption></figure><p>In fact, winners averaged an additional 1.34 RB’s per week on their roster meaning they generally used 2 of their 3 flex spots for RB’s.</p><p>And taking a look at net wins calculated as (#Wins — #Losses), we see that RB’s also have a slight edge over WR’s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*r8HozVpuGq0tTeVKj4Upwg.png" /></figure><p>So, at least in this half PPR league, it seems to make sense to lean slightly on RB’s more than WR’s.</p><h3>DRAFTS — How do we create a winning roster?</h3><p>This specific league is a redraft league meaning at the beginning of the year, everyone starts from scratch and has to build their initial roster through a draft process where each user’s draft position is randomized.</p><p>The draft process is centered around Average Draft Position <strong>(ADP) </strong>which ranks all fantasy-relevant NFL player based on real mock drafts that anyone can participate in on websites like ESPN and Yahoo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3zCoeG-zhblI2OvNV_Jn1g.png" /></figure><p>The above dashboard looks overwhelming but it’s functionality is mostly based on using the top left draft board as a filter to narrow the data. The draft board represents four years of previous draft picks including:</p><ul><li>Pick (overall)</li><li>Pick (within a round)</li><li>Which player was drafted by which user (users REDACTED)</li><li>That player’s avg fantasy output per game</li><li>Colorization compares that player’s avg fantasy points against that position’s mean average for that year…</li><li>Which means deep red = extreme underperformer…</li><li>And deep green = extreme overperformer</li></ul><p>With this roadmap we can quickly find over- and under-performers and when we filter by clicking on them we get more useful information that can help us decide on their potential fantasy value next year.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*49Fu_cFEWi7SZwEw1CjjXA.png" /><figcaption>Using the draftboard (top left) to filter shows us useful information about that player’s trends</figcaption></figure><h4>EXAMPLE</h4><p>After filtering for the 10th overall (round 2.4) pick from 2023 we see Saquon Barkley was drafted here and by which user (redacted). Additionally we can see:</p><ol><li>Saquon’s Avg fantasy points per game over time</li><li>Saquon’s Net Wins over time</li><li>Total fantasy points Saquon scored for a specific user (redacted) in the year filtered</li><li>Total points Saquon scored for all users who drafted him</li><li>Avg point output relative to others at his position (in this case other RBs)</li><li>Saquon’s Age trend over time</li></ol><p>Remember that draft position for the users is randomized every year so for this league whether you’re in the 1st — 6th spot changes and users do not have control over this. The draft is a game of opportunity cost and to some extent, psychological warfare. If your opponent has the next pick after you and you know they have their eye on a specific player, you can infer that player has value and deprive them of that player — a true zero-sum game.</p><blockquote>But, putting malice aside, is there a better way to choose which players to take in which rounds?</blockquote><p>History may be able to help with, you guessed it, another dashboard!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*VtGqTozwHaPDdzy2xisDXQ.png" /></figure><blockquote><strong>Hint: try to draft in the green zones.</strong></blockquote><p>This takes the average fantasy production per game of a position and aggregates it based on where those players were drafted. This allows us to evaluate pick slots against others based on position and fantasy output —</p><blockquote>- exactly the kind of information that can help a user decide on who to draft and where to draft them.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*vFs4pf3Im5Wnq4yVdBy6bQ.png" /><figcaption>Filtered for Saquon Barkley</figcaption></figure><p>So here we can see Saquon’s fantasy output based on which slot he was drafted in. Ironically, his best output per game was when he was drafted lowest (normally we would expect the opposite).</p><p>While the filter is handy, the pick slots are more useful without filtering. Let’s take the 1.5 (5th overall) round pick for WR’s/RB’s for example. It shows a value of 17.8 — a deep green which is a good sign. To average this kind of fantasy output per game for an entire season would have a <em>massive </em>impact.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*9g0aUjS7KIAsq9QUNn1F_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*CTDK90nB9LRLz_cU7bWP0A.png" /></figure><p>The 17.8 is the average fantasy output per game of all WR’s and RB’s drafted at that same spot. What this means is that, if you’re considering an RB or WR in the draft, the 1.5 slot has actually historically been the best of all 6 first round picks.</p><blockquote>We can use this data to construct zones where it’s more optimal to take certain positions and less optimal to take others. Again, opportunity cost is the name of the game here.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*3_e_OS_m4dy3Q8IwdtlSPA.png" /><figcaption>RB / WR Deadzone</figcaption></figure><blockquote>The 5th — 8th rounds (above) have historically been bad for WR/RB. What kind of TE or QB might we be able to draft in this zone?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/178/1*rSYHt6G7HxbB86OBBTdJoQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/175/1*jYdRtC0AdSXY8agrTGZOJg.png" /><figcaption>Quarterbacks (LEFT) — Tight Ends(RIGHT)</figcaption></figure><p>Historically, this has been a pretty good time to grab a quarterback, particularly in the 5th — 7th rounds. The 7th round has also been a decent round to draft a Tight End.</p><h3>NFL Player Trends — Winners and Losers</h3><p>Ahead of the draft and during the season, there are certain players we may want to target. There will always be certain players that most people are targeting which means they will be more difficult to get.</p><h4>Is there a way to identify “sleepers” — players that are undervalued by the consensus?</h4><p>One way of evaluating players would be mapping their usage to their net wins. If we divide these into quadrants we can better understand if there are <strong>players we should be using less (bottom right) or more (top left).</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d2jgJT2qaAqQlDQXWFfW2A.png" /><figcaption>X-axis ← Less Usage | More Usage →</figcaption></figure><p>Combining these into a dashboard with filters allows us to drill down into whether these are truly useful or just noise. Let’s focus on a player in the “Should be used more?” quadrant.</p><h4>EXAMPLE</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*PQ2GMm-vpIydvoDnrQ429w.png" /><figcaption>Rhamondre Stevenson — an underutilized player with a +4 positive net win differential</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*yiwe2wyWeRo4-K3NfvqJng.png" /><figcaption>Rhamondre Stevenson — Fantasy Output over time per game (net wins trending green which is good)</figcaption></figure><p>So it’s fair to say that historically, Rhamondre Stevenson is mostly trending in the right direction as far as net wins and fantasy points and could be a good candidate for a fantasy roster.</p><h3>NFL Player Trends — Usage vs Fantasy Output</h3><p>Another popular metric for identifying players who are potentially being over or under-used would be mapping their usage to their fantasy output.</p><p>Using a best fit line we can visualize which players may be over or underperforming.</p><h4>Caveats</h4><p>There are some players here that are no longer relevant (active) and so will not be considered as candidates.</p><p>Also, we will lean away from recommending candidates from the far left side which has higher risk of small sample bias, often caused by players stepping in as “spot starts” or becoming relevant for only a few games due to injuries from other players on their team. The exceptions to this rule will be for players who are obviously not these type of “spot starts” like Kirk Cousins who has played the majority of his potential total games.</p><blockquote>Hint: Use players in green zone more, user players in the red zone less.</blockquote><p>Further from the line = stronger candidate</p><h3>QUARTERBACKS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bnAPb8FZrwsHFMwPg6JBmQ.png" /><figcaption>Quarterbacks</figcaption></figure><p><strong>CANDIDATES FOR HIGHER USAGE?:</strong></p><ul><li>Kirk Cousins</li><li>Dak Prescott</li><li>Justin Fields</li></ul><p><strong>CANDIDATES FOR LOWER USAGE?:</strong></p><ul><li>Lamar Jackson</li><li>Trevor Lawrence</li></ul><h3>RUNNING BACKS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jYdG26gMgsiZwpZCnj0l5w.png" /><figcaption>Running Backs</figcaption></figure><p><strong>CANDIDATES FOR HIGHER USAGE?:</strong></p><ul><li>De’Von Achane</li><li>Breece Hall</li><li>Kyren Williams</li></ul><p><strong>CANDIDATES FOR LOWER USAGE?:</strong></p><ul><li>Bijan Robinson</li><li>Zack Moss</li><li>James Cook</li></ul><h3>WIDE RECEIVERS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qy9OU79DMBR-1avEGGEhNA.png" /><figcaption>Wide Receivers</figcaption></figure><p><strong>CANDIDATES FOR HIGHER USAGE?:</strong></p><ul><li>Rashee Rice</li><li>Tank Dell</li><li>Elijah Moore</li></ul><p><strong>CANDIDATES FOR LOWER USAGE?:</strong></p><ul><li>Robbie Chosen</li><li>Nico Collins</li><li>Corey Davis</li></ul><h3>TIGHT ENDS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UpF8Dz-01VeHFB39IJm5xQ.png" /><figcaption>Tight Ends</figcaption></figure><p><strong>CANDIDATES FOR HIGHER USAGE?:</strong></p><ul><li>David Njoku</li><li>Trey Mcbride</li></ul><p><strong>CANDIDATES FOR LOWER USAGE?:</strong></p><ul><li>Robert Tonyan</li><li>Dawson Knox</li></ul><h3>Other Interesting Findings</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*KSXHPiQjGr6jgsHX_PIcAA.png" /><figcaption>User points scored by their drafted players</figcaption></figure><p>The chart above shows the number of points drafted players scored for each user (redacted) that drafted them and the blue circles are the league winners. Importantly, this does NOT show a user’s<em> total </em>fantasy points for a season, hence the title of the chart.</p><blockquote>The 2021 and 2023 winners actually had some of the <em>LOWEST</em> fantasy output from their drafted players. Consequentially — the draft is important — but TRADES AND WAIVER WIRE PICKUPS ARE CRITICALLY IMPORTANT!</blockquote><p>Take a look at the same chart except this includes ALL player points scored for a user in a given year:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*E0jok3RDkzrcwrYllkrMeQ.png" /></figure><blockquote><em>None of the league winners had the highest absolute fantasy points in the year they won…</em></blockquote><p>As mentioned before, it doesn’t matter if you win by 1 or 50 points — the win is all that matters. Lady luck does help pave the way to fantasy glory. This relates back to the fact that it does not matter if you win by a large or small margin.</p><h3>Areas not specifically covered in this analysis</h3><p>There are a few important areas that are yet to be covered in depth:</p><ul><li>Trades</li><li>Player Fantasy Output Variance</li><li>Waiver Wire Pickups</li><li>Kickers</li><li>Forward Projections</li></ul><h4>Trades</h4><p>Trades can have a large impact on a user’s season as we’ve noted. It’s best to remember that trades are easiest to execute when a normally high-producer goes through a rough patch or when a typical under-performer hits a temporary hot streak. This leads to the next point —</p><h4>Player Fantasy Output Variance</h4><p>I’ve coined the following “70–30 rule” for fantasy football:</p><blockquote>If you’re 100% sure about something, then you’re actually only 70% certain. If you think something has a 0% change of happening, it’s actually closer to 30%.</blockquote><p>Player performance on any given week is unpredictable. This is largely a function of injuries and the outsized impact that touchdowns have on fantasy output but there are other factors at play such as coaching scheme, home vs away games, weather, etc. This doesn’t mean that some players aren’t more predictable than others and this is where the concepts of “floor” and “ceiling” come into player performance analysis, more commonly known as “risk” vs “reward”.</p><h4>Waiver Wire Pickups</h4><p>Approximately 37% of the points scored by the winners in 2021 and 2023 came from players they found on waivers or traded for. <em>The importance of these players cannot be overstated</em>. Like the draft, the waiver wire is a zero-sum game. When in doubt, be aggressive, spend your faab and get the potential league-winner before your opponents.</p><h4>Kickers</h4><p>Kickers only accounted for 6% of weighted fantasy output in this league. Interestingly, they had a slight negative relationship with net wins. This was largely due to the fact that certain users preferred to keep an additional high-leverage position, usually a WR or RB, on their bench rather than put a kicker on their active roster. This deprived their competition of that player and those users did, in fact, tend to win more. This means depriving the competition from having the higher leverage WR / RB position at the expense of a kicker is a viable strategy.</p><h4>Forward Projections</h4><p>Projecting how a player will perform in the upcoming season is outside the scope of this analysis. We can use a player’s previous year’s performance plus or minus changes in team composition and trades to estimate what next year will look like but as of 03.21.24 there are too many potential unknowns to model.</p><h3>Client Recommendations</h3><ul><li>Running Backs and Wide Receivers contribute the vast majority (70%) of fantasy points to a team — <em>be thoughtful and prioritize these positions, both in the draft and when setting weekly lineups</em></li><li>Running Backs have a slight edge over Wide Receivers both in terms of fantasy output and correlation to weekly wins and overall league wins — <em>if you can’t decide between a running back or wide receiver for that last lineup spot, lean towards running back</em></li><li>Avoid position-specific dead zones while drafting and consider drafting another position. <em>Your default choice should be WR/RB but keep an eye on where these tend to underperform and consider QB/TE in these zones.</em></li><li>Lean towards drafting and using players in the “Should be used more?” quadrant</li><li>Lean away from drafting and using players in the “Should be used less?” quadrant</li><li>Be vigilant on your waiver wire pickups and trades</li></ul><h3>Does this analysis apply to your fantasy league?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HQIjqbX9pHTLU51dYW4DKA.png" /><figcaption>A salt shaker containing large grains of salt</figcaption></figure><p>The short answer is, probably not.</p><p>The longer answer is that, the general strategies will be similar, but the impact will be different.</p><p>The main differences come from the number of flex positions and (obviously) the number of users in the league.</p><p>A 6-user league will only focus on the top ~25 ranks for WR and RB while a 12 user league will need to rely on more fringe players up to rank 30.</p><p>For the smaller league, only the top ~6 QB/TE’s will be relevant while a typical 12 user league will be more interested in the top 12 at the QB/TE positions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*ce7dbJLYQE1VvSU6431TDw.png" /><figcaption>QB/TE become more important in larger leagues with the typical single flex position</figcaption></figure><p>Here we need to take a moment to explain tiers. These are meant to group similar fantasy producers together. As an example, while Josh Allen (Rank 1) and Patrick Mahomes (Rank 4) are 3 spots apart, there’s likely to be a larger difference between between Patrick Mahomes (Rank 4) and C.J. Stroud (Rank 5). In other words,<strong> the difference between ranks 1 and 4 is actually smaller than between ranks 4 and 5 </strong>because of a tier cliff.</p><p>The idea is that if you’re nearing the bottom of a tier, it may make sense from a draft (or trade) strategy standpoint to veer away from RB/WR and go for a QB/TE. In a larger league, this decision becomes more critical.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d5vVgWy1BOd9k-YdHMnNiQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uFmEH5NDEskNj6cdkUDJsA.png" /></figure><h4>So users of a 12 person league:</h4><ol><li>Get more relative fantasy production from their QB/TE</li><li>May depend on a lower tier (worse production) from these two positions</li></ol><p>While the majority (62%) of total fantasy production still comes from RB/WR…</p><blockquote>… a 12 user league will shift the QB/TE priority higher.</blockquote><p>Some leagues also score a QB throwing touchdown as 6 fantasy points instead of 4. This would further increase the importance of the QB position.</p><h4>PPR — Points Per Reception</h4><p>Our analysis is based on a half PPR league but there are also Full PPR and No PPR leagues, although the latter is rare. A half PPR league gives .5 fantasy points per reception while full PPR awards a full point for a reception.</p><blockquote>In a full PPR league it’s likely that the RB advantage noted in this analysis dissipates and moves to parity with WR’s. In fact, WR’s may have the edge in a full PPR format.</blockquote><h3>EARLY RETROSPECTIVE — Project Technical Overview</h3><p>Roughly 60% of project hours were spent on ETL (Extract — Transform — Load) while the other 40% was spent on actual analysis which involved:</p><p>13 — Tableau workbook iterations</p><p>110 — Tableau worksheets</p><p>7 — Tableau dashboards</p><p>In the end, we got down to the valuable insights our client needed but there are certainly further unmined insights that we’ll explore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X-4VsBUovSMGQgvO5WpnBA.png" /></figure><h4>Areas for deeper exploration and analysis</h4><ul><li>Trades</li><li>NFL Player Variance</li><li>NFL Teams</li><li>Waiver Wire Pickups</li><li>Kickers</li><li>Defenses</li><li>Touchdowns</li><li>Injuries</li><li>NFL Player Age</li><li>Forward Projections</li></ul><blockquote>If you found this useful please forward to others that may also find it useful. Just make sure you’re not competing against them next season!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54e00e3b48e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[In Search of Fantasy Glory (Part I)]]></title>
            <link>https://medium.com/@seanlukeholland/in-search-of-fantasy-glory-part-i-3f217dde772a?source=rss-f5efeadb387a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f217dde772a</guid>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fantasy-football]]></category>
            <category><![CDATA[football]]></category>
            <category><![CDATA[tableau]]></category>
            <dc:creator><![CDATA[Sean Holland]]></dc:creator>
            <pubDate>Thu, 25 Jan 2024 17:37:01 GMT</pubDate>
            <atom:updated>2024-03-24T17:55:29.342Z</atom:updated>
            <content:encoded><![CDATA[<p>Part II — Analysis can be found (<a href="https://medium.com/@seanlukeholland/how-to-win-your-fantasy-football-league-54e00e3b48e7">here</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XUHni-BahrctJrEOoRAwCA.png" /></figure><p>Let’s build a database from scratch, shall we?</p><p>Actually, let’s build the entire data pipeline, what could go wrong?</p><p><strong>Why Fantasy Football? </strong>It’s got a LOT of stats… rushing yards, receiving yards, receptions, yards per attempt, the list goes on and on. Sports are a veritable gold mine when it comes to data. Honestly, there’s a LOT of luck involved with this “sport” but perhaps we can glean some insights.</p><p>First though, we’re going to need to build the data pipeline. The whole thing. This is part one of a two part post and will document my ETL (Extract, Transform, Load) process for building the pipeline. Part two will focus more on the analytics and insights drawn from the data.</p><p>The overall pipeline looks like this:</p><p>Sleeper API data extraction =&gt; Build Tables in Excel =&gt; Analyze via Tableau</p><h3>DATA — what do we need?</h3><p>Before pulling data we need to describe the types of analysis we might want to do and which data we might be able to use to accomplish these types of analyses.</p><h4>USER DATA</h4><ul><li>Win / loss trends</li><li>Roster composition</li><li>Activity like trades, waiver wire pickups, player drops</li></ul><h4>PLAYER DATA</h4><ul><li>Fantasy scoring trends</li><li>Win / loss trends</li><li>NFL team data like wins / losses</li><li>Player position (wide receiver, running back, etc)</li></ul><h4>DRAFT DATA</h4><ul><li>User draft order</li><li>Average consensus draft position (commonly known as ADP)</li><li>Average ACTUAL draft position</li></ul><p>With these data “guideposts” in mind, we’d like to understand the relationships between and among these data points with one major goal:</p><blockquote><em>increase the odds of winning our fantasy league</em></blockquote><p>Data interrogation might include questions like:</p><ul><li>When does it make sense to “reach” for a player (draft them significantly ahead of their ADP ‘Average Draft Position’ )</li><li>Do certain players help you win or lose more often?</li><li>What team composition makes the most sense? Should we prioritize wide receivers over running backs?</li><li>Do certain positions have a prime “window” of fantasy production?</li><li>Do certain users favor certain players or certain positions? What win/loss trends, if any, accompany these preferences?</li></ul><p>This league competes using the Sleeper App and API documentation can be found <a href="https://docs.sleeper.com/">here</a>. At first I was just running test GET commands to see what kind of data I had access to.</p><p>This led me to a couple github repositories of others who created API wrappers including <a href="https://github.com/dtsong/sleeper-api-wrapper">this one</a> and eventually <a href="https://github.com/joeyagreco/sleeper">this one</a> which ended up being very helpful in pulling the data I would need via python. Thanks to <a href="https://joeyagreco.medium.com/">Joey Greco</a> for his work on this repository.</p><h3>DATA LANDSCAPE — PYTHON DATA EXTRACTIONS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OE5eCMWbPndy7wy0sG4ATQ.png" /></figure><p>After some testing it appeared the largest data sets we’d be working with included around <strong>9000 rows of NFL player data </strong>with stats like name, position, team, age, etc.</p><p>However, only about 1–3% of players are fantasy relevant in any given year so really we’re talking more like 150–300 rows.</p><p>At the highest level of granularity (or the bottom of the one-to-many table waterfall) we’d have a data set where each row represented an individual NFL player’s fantasy performance for a given week. Our baseline data, which was helpful for verifying that we did, indeed, have the <em>correct </em>data involved several key entities or data guideposts:</p><ul><li>Seasons (4)</li><li>Users (6)</li><li>Rosters (6– a 1:1 relation with Users)</li><li>Weeks (67)</li><li>Players (~300 fantasy relevant NFL players)</li><li>Matchups</li></ul><p>The NFL season is currently 18 weeks long and every team plays 17 times and gets one BYE week for recovery. Also fantasy season championships typically occur in the penultimate week of the normal NFL season before playoffs to avoid issues created when teams decide to rest their starters if they have “nothing to play for”.</p><ul><li>2020–16 weeks (before the NFL moved to an 18 week season)</li><li>2021–17 weeks</li><li>2022–17 weeks</li><li>2023–17 weeks</li></ul><p>Given the number of weeks and other important entities listed above, the shape of our python outputs might have row totals that look something like this:</p><ul><li>Matchups — 197</li><li>Win/Loss Outcomes — 394</li><li>NFL Player Fantasy Performances — 4,422 (max)</li><li>Weeks — 67</li></ul><p>After lots of iterations the following code was able to pull a lot of good league matchup data:</p><pre>def extract_matchup_info(matchups):<br>    extracted_info = []<br>    for matchup in matchups:<br>        # Extract relevant information from each matchup<br>        info = {<br>            &quot;matchup_id&quot;: matchup.matchup_id,<br>            &quot;roster_id&quot;: matchup.roster_id,<br>            &quot;points&quot;: matchup.points,<br>            &quot;starters&quot;: matchup.starters,<br>            &quot;starters_points&quot;: matchup.starters_points<br>        }<br>        extracted_info.append(info)<br>    return extracted_info<br><br><br>if __name__ == &quot;__main__&quot;:<br>    # Define league IDs with corresponding start dates and number of weeks<br>    leagues = {<br>        &quot;6redact4&quot;: {&quot;start_date&quot;: &quot;2020-09-10&quot;, &quot;weeks&quot;: 16},<br>        &quot;7redact8&quot;: {&quot;start_date&quot;: &quot;2021-09-09&quot;, &quot;weeks&quot;: 17},<br>        &quot;8redact0&quot;: {&quot;start_date&quot;: &quot;2022-09-08&quot;, &quot;weeks&quot;: 17},<br>        &quot;9redact4&quot;: {&quot;start_date&quot;: &quot;2023-09-07&quot;, &quot;weeks&quot;: 17}<br>    }<br><br>    # Initialize a list to hold all matchup data across all leagues and weeks<br>    all_data = []<br><br>    # Iterate through each league and its weeks<br>    for league_id, details in leagues.items():<br>        for week in range(1, details[&quot;weeks&quot;] + 1):<br>            weekly_matchups = LeagueAPIClient.get_matchups_for_week(league_id=league_id, week=week)<br>            extracted_matchups = extract_matchup_info(weekly_matchups)<br>            for matchup in extracted_matchups:<br>                matchup[&#39;week&#39;] = week  # Add the week number to the data<br>                matchup[&#39;season_start&#39;] = details[&quot;start_date&quot;]  # Add the season start date to the data<br>                matchup[&#39;league_id&#39;] = league_id  # Add the league ID to the data<br>                all_data.append(matchup)<br><br>    # Convert the list of matchup data to a DataFrame<br>    df_matchups = pd.DataFrame(all_data)<br><br>    # Define the file path for the Excel file<br>    excel_filepath = r&#39;C:\REDACTED\compression_test_01_12_24.xlsx&#39;<br><br>    # Write the DataFrame to an Excel file<br>    df_matchups.to_excel(excel_filepath, index=False)<br><br>    print(f&quot;Weekly matchup data for all leagues saved to {excel_filepath}&quot;)</pre><p>Which resulted in data shaped like this (league_id redacted):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5o-XA-yjLAUQ2iLkiXfcUg.png" /></figure><p>Rows here represent the NFL players on a specific roster and how they performed on specific week. To analyze the data in Tableau, we need to pivot this data and expand it. Down the line we’ll also need to connect the starters (represented here as 4-digit strings) with their names to make analysis easier. It will also help to create unique ids for table joining further down the line.</p><p>From here it made sense to add code to create a week_date and unique_weekly_id column for potential joins and table design later. An important field we were missing at this point was wins and losses which involved comparing row level total points scored between the two rosters that played each other in a given week. Given the data structure we had up to that point, this involved matching up roster_ids that played each other in a given week as defined by their shared matchup_id. However, each week these matchup_ids repeated with values of 1–3 and since one week was represented by every 6 rows, this required some additional logic to understand who played who each week and the result of that matchup.</p><p>The below code modifies the file output from our previous code to add win/loss data based on logic that:</p><ul><li>sums the list object of starter_points (starters being the NFL player who played that week as opposed to players on a roster’s bench which do NOT play)</li><li>finds a row’s opponent based on matchup_id within batches of 6 rows (6 rows representing a single week)</li></ul><pre>import pandas as pd<br>import json<br>import os<br><br>excel_filepath = r&#39;C:\U&#39;<br><br>df_matchups = pd.read_excel(excel_filepath, sheet_name=&#39;RAW - Weekly Matchup&#39;)<br><br>def parse_and_sum_points(points_str):<br>    try:<br>        points_list = json.loads(points_str.replace(&quot;&#39;&quot;, &#39;&quot;&#39;))<br>        return sum(points_list)<br>    except json.JSONDecodeError:<br>        return 0<br><br>df_matchups[&#39;total_points&#39;] = df_matchups[&#39;starters_points&#39;].apply(parse_and_sum_points)<br>df_matchups[&#39;result&#39;] = &#39;&#39;<br><br>def assign_win_lose(group):<br>    sorted_group = group.sort_values(by=&#39;total_points&#39;, ascending=False)<br>    sorted_group.iloc[0, sorted_group.columns.get_loc(&#39;result&#39;)] = &#39;WIN&#39;<br>    sorted_group.iloc[1, sorted_group.columns.get_loc(&#39;result&#39;)] = &#39;LOSE&#39;<br>    return sorted_group<br><br>results = []<br>for i in range(0, len(df_matchups), 6):<br>    df_subset = df_matchups.iloc[i:i+6]<br>    df_subset_grouped = df_subset.groupby(&#39;matchup_id&#39;).apply(assign_win_lose).reset_index(drop=True)<br>    results.append(df_subset_grouped)<br><br>final_df = pd.concat(results)<br><br>new_file_name = &#39;weekly_matchup_comp_WIN_LOSE 01.12.24.xlsx&#39;<br>new_excel_filepath = os.path.join(os.path.dirname(excel_filepath), new_file_name)<br><br>final_df.to_excel(new_excel_filepath, index=False)<br><br>print(f&quot;Processed matchup data saved to {new_excel_filepath}&quot;)</pre><p>Which resulted in this data structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iqsuRbV2VQxhxpcpZhHQhw.png" /></figure><h4>THE WIN LOSS DATA CONUNDRUM — an aside</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FC1VjqMn51ZLhZtqY4ZcFw.png" /><figcaption>Wins, you say? AND losses?</figcaption></figure><p>Here I need to take a small aside as the win/loss journey was a learning process for me. It was longer and more painful than anticipated but it did help sharpen my ability to better understand the right tool for the job at hand. Before ultimately using python it went something like this:</p><ol><li>Helper columns and pairing functions — excel</li><li>VBA scripting — excel</li><li>MS Powerquery using interleave and index columns</li><li>SQL window functions</li><li>Back to python</li></ol><p>To streamline a data pipeline we want to move the “right” amount of the ‘T’ in the ETL process into the ‘E’ step or whatever step we can modify for automation. Typically this means wherever we can write iterative code logic (VBA / Python) as opposed to manually moving the data around ourselves (Excel, Power Query, SQL).</p><p>Also, I was surprised at how difficult it was to load this into MySQL Workbench. You have to be <em>very precise</em> with the data types during this process and this required so much trial and error that I discarded it based on the fact that this opened up far too much latitude for human error in a process that we eventually want to make as automated as possible.</p><h4>BACK TO EXTRACTION AND TRANSFORMATION!</h4><p>At this point we’re at the data granularity level for <em>users</em> which we know from our data guideposts from earlier should be 394 unique win loss data points for all rosters combined. Since roster has a one-to-one relationship with users this means we’re now getting the win/loss picture for each user.</p><p>But based on the kinds of analysis we need to do, we need to get more granular and understand NFL player fantasy performance on a weekly basis which means we need to pivot the data in the starters and starter_points columns.</p><pre>def extract_matchup_info(matchups, week):<br>    extracted_info = []<br>    for matchup in matchups:<br>        info = {<br>            &quot;matchup_id&quot;: matchup.matchup_id,<br>            &quot;roster_id&quot;: matchup.roster_id,<br>            &quot;points&quot;: matchup.points,<br>            &quot;starters&quot;: matchup.starters,<br>            &quot;starters_points&quot;: matchup.starters_points,<br>            &quot;week&quot;: week  # Include the week information<br>        }<br>        extracted_info.append(info)<br>    return extracted_info<br><br><br>if __name__ == &quot;__main__&quot;:<br>    # Define the league IDs with their respective week ranges<br>    leagues = {<br>        &quot;6redact4&quot;: 16,  # 2020 league with 16 weeks<br>        &quot;7redact8&quot;: 17,  # 2021 league with 17 weeks<br>        &quot;8redact0&quot;: 17,  # 2022 league with 17 weeks<br>        &quot;9redact4&quot;: 17   # 2023 league with 17 weeks<br>    }<br><br>    all_leagues_data = []<br><br>    # Loop through each league<br>    for league_id, total_weeks in leagues.items():<br>        matchup_data = {}<br><br>        # Loop through the weeks specific to each league<br>        for week in range(1, total_weeks + 1):<br>            weekly_matchups = LeagueAPIClient.get_matchups_for_week(league_id=league_id, week=week)<br>            extracted_matchups = extract_matchup_info(weekly_matchups, week)  # Pass week here<br>            matchup_data[f&quot;Week {week} Matchups&quot;] = extracted_matchups<br><br>        # Convert to DataFrame and append to all_leagues_data<br>        df = pd.DataFrame([item for sublist in matchup_data.values() for item in sublist])<br>        all_leagues_data.append(df)<br><br>    # Combine all league data into a single DataFrame<br>    combined_df = pd.concat(all_leagues_data, ignore_index=True)<br><br><br>    # Prepare for expansion of rows<br>    expanded_data = []<br>    for index, row in combined_df.iterrows():<br>        # Check if starters and starters_points are lists<br>        if isinstance(row[&#39;starters&#39;], list) and isinstance(row[&#39;starters_points&#39;], list):<br>            starters = row[&#39;starters&#39;]<br>            starters_points = row[&#39;starters_points&#39;]<br>            if len(starters) == len(starters_points):<br>                for starter, point in zip(row[&#39;starters&#39;], row[&#39;starters_points&#39;]):<br>                    expanded_data.append({<br>                        &#39;matchup_id&#39;: row[&#39;matchup_id&#39;],<br>                        &#39;week&#39;: row[&#39;week&#39;],  # Get week from the row<br>                        &#39;roster_id&#39;: row[&#39;roster_id&#39;],<br>                        &#39;starter&#39;: starter,<br>                        &#39;starter_points&#39;: point<br>                    })<br><br># Create a new DataFrame from the expanded data<br>expanded_df = pd.DataFrame(expanded_data)<br><br># Define the output file path<br>output_file_path = r&#39;C:U\redact.xlsx&#39;<br><br># Save the new DataFrame to an Excel file<br>expanded_df.to_excel(output_file_path, index=False)<br><br>print(f&quot;Data transformation complete. Expanded data saved to &#39;{output_file_path}&#39;&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*-BHdYfj3e1uTz7hULMGgAg.png" /><figcaption>Excel Output from Python</figcaption></figure><p>From here we should have enough data to start being able to answer some of the important questions we outlined earlier.</p><p>But how do we structure the data so that it plays nice with Tableau? For that we’ll need to enter the world of entity relationships and table design.</p><h3>DATA TRANSFORMATION AND PREPARATION</h3><p>For this step I needed to dive deep down the Tableau rabbit hole. Originally I thought I wanted to make a 3NF (third normal form) database and if that was done correctly it should be a piece of cake to load into tableau. This process went through a <em>lot </em>of iterations and in the end, I learned your data set and table design does not necessarily need to be <em>fully</em> normalized. The level of granularity is more important and for this analysis we have two distinct levels of granularity — one at the <em>NFL player level</em> and one at the <em>fantasy user level</em>. Tableau has some good tools for handling the combining of tables but I found that Tableau Prep was actually the better tool for this part of the process.</p><p>Tableau’s native “relationships” are supposed to be their more intuitive way of joining data sets together but with different levels of granularity these weren’t sufficient and with some quick testing it was obvious Tableau wasn’t correctly relating these fields. Relationships’ advantage is that aggregations of measures happen BEFORE any table joining that Tableau will do when we create a visualization. The problem with Tableau’s native JOIN functionality is this “flattens” your data to the highest (most granular) level which would have resulted in ~25M rows in our case.</p><p>Some additional quick testing showed that our normalized database was not correctly aggregating data with JOINS or relationships. User’s wins and losses should total to ~67 weeks with a little bit of variance for users that didn’t make it into the championship round in the final week.</p><p>And NFL player’s total wins/losses should reflect ~17 per season games (max) if they’re a player being used week-in and week-out.</p><p>Before we get to tableau Prep let’s summarize the table design process.</p><h4>TABLE DESIGN</h4><p>After lots of iterations this was the first database design for our fantasy database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*aTKFyafq-x3tgJfX8xXWyA.png" /><figcaption>Foreign Keys marked with purple</figcaption></figure><p>This design resulted in the granularity and data blending issues I mentioned earlier. While Tableau couldn’t handle this design, table Prep ended up being the right tool. I did work through some iterations of de-normalizing the tables themselves in Excel but it proved faster and easier to handle JOIN issues using Tableau Prep.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v-33Ig6JWt87zZlYUdl5UA.png" /><figcaption>The table joining process — Tableau Prep</figcaption></figure><p>Prep has enhanced functionality and visualizations that allow you do build a visual step by step work flow. Key elements included:</p><ul><li>Removing duplicate joined fields</li><li>Colorization to really understand which data is being joined and what the data set will look like pre and post join</li><li>Multiple join clauses which was key for joining the player performance data with the user level roster makeup and win/loss data</li><li>Quick ability to visualize the different join types</li><li>Discerning which data will remain and which will be discarded which was useful when joining the player_info table of which only about 300 of the 9000 rows were relevant</li><li>Data type edits — it turned out date_week, an incredibly important field, was not in the correct date-type format</li><li>Selection/visualization of data during the JOIN process to validate your data during each step — a <strong>HUGE </strong>time saver.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sgojmAduLCkR6aeNyzogtg.png" /></figure><p>As an example, the JOIN above shows we’re using an INNER JOIN to connect our current data set based on the player_id field and confirms the table sizes pre and post-join with a quick summary of what the data set actually looks like (bottom right). So I knew after this JOIN that we’d have 4299 individual player performance data points.</p><p>To validate this you can select different data points in the tables on the top right as a “filter” that highlights the relevant connected data points:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DIj6R32J-RxA-3O8iEhoiQ.png" /></figure><p>In the above screen shot I selected a specific user_id knowing I should see a certain number of wins. The 374 told me that this was aggregating wins at the NFL player level, NOT the user granularity level so I knew there would be additional work that needed to be done to correctly visualize user level data.</p><blockquote>This is a <em>MUCH </em>quicker process than transforming the data and loading it into Tableau and <em>THEN </em>validating.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qIvRdmaarpSfxsJ_6_JYtg.png" /><figcaption>Two separate JOIN flows to create two separate data sources to analyze in Tableau</figcaption></figure><p>After some quick testing it became clear I could use these two data sources in Tableau for analysis and data aggregations looked correct. There were no JOINs or creation of relationships necessary once the data outputs from Prep were loaded into Tableau Desktop.</p><h4>THE “FINAL” DATA SET(S)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*GvwW27F5a2NGVboxsfFx3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*U1LC66i85-ZAOb6hdOoAGw.png" /><figcaption>(LEFT) NFL Player level data | (RIGHT) User level data</figcaption></figure><p>With these two handy and both loaded into Tableau we can now dive into better understanding whether there’s info here that can help us navigate the road to fantasy glory.</p><blockquote>The ultimate goal: Crush the opposition — Win the league</blockquote><h3>BEYOND THE LOAD</h3><p>After hours of data visualizations, trends and charts I sent this chart to confidantes to get some feedback:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s-MP2UijEPdysP7PGkkKLA.png" /><figcaption>Average Fantasy Points Scored by NFL Team — Net Fantasy Wins/Losses Scaled Green (more wins) to red (more losses)</figcaption></figure><p>And I got an offhand response:</p><blockquote>“I can’t believe the Jets are so high”.</blockquote><p>At first I attributed this to Breece Hall, a phenom running back in his sophomore year but after further digging I found that Aaron Rodgers, who played only a single drive in the 2023 season for the Jets was contributing a huge number of fantasy points to the Jets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*WiwH02Oqv6iBu8jRJxTUmA.png" /></figure><blockquote>Things that suck but are critical:</blockquote><blockquote>- Feedback and iteration</blockquote><blockquote>- Domain knowledge</blockquote><p>Make sure to standardize a feedback process to help break free from your own assumptions. The reason I was able to quickly identify the issue here (after it was brought up to me by someone else) is that I have domain knowledge.</p><p>Rodgers’ numbers immediately jumped out at me when I broke down fantasy point contribution by player for each team. The majority of Rodgers’ fantasy points came from his time with the Packers. If you lack the domain knowledge than you need to lean even harder on the feedback process. Find people who know. Talk to them.</p><blockquote>I’d found a fundamental problem with specific data in the player_info table.</blockquote><p>The data itself was correct but the table represented dynamic information as static. All data in the table was current as of the 2023 season. <em>That meant that the following data would be unreliable in any time-series analysis:</em></p><ul><li>years_experience</li><li>weight</li><li>age</li><li>active</li><li>team</li><li>number</li></ul><p>BUT… Since years_experience and age can be extrapolated in Tableau with a calculated field based on week_date, these wouldn’t prove too problematic. Also a player’s weight isn’t likely to change too much from year to year. Whether a player is active isn’t a dimension we care much about since the only relevant players are the active ones and a player’s number is also irrelevant for analyzing performance.</p><p>So even though this looked like it could be a disaster we really only have one dimension here worth fixing: team. Unfortunately at this point in time the <a href="https://www.fantasypros.com/">historic data I have access to</a> is inaccurate with respect to a player’s historic team so any analysis based on an NFL player’s team will have to wait.</p><p>Oh well… onto Part II — data analysis!</p><h3>EARLY RETROSPECTIVE — Technical overview</h3><p>Forging a new path for the first time takes a lot of work and requires a lot of documentation. Below is a rough outline of the steps taken here, not including Tableau testing:</p><p>15 — entity relationship diagram iterations</p><p>357 — lines of code: draft data</p><p>666 — lines of code: user performance data</p><p>135 — lines of code: NFL player info data</p><p>2 — sleeper API wrappers</p><p>2 — SQL extracts</p><p>26 — Excel master workbook iterations</p><p>5 — VBA workbook testing iterations</p><p>24 — Historic player workbook transformations</p><p>4 — Power Query workbook iterations &amp; transformations</p><p>75 — Excel worksheets: final master workbook with tables</p><p>9 — Tableau Prep iterations</p><p>4 — “Final” Tableau Data Sources</p><blockquote>** A quick note: Draft data will be included further down the line after we’ve done some analysis of our current data sets.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f217dde772a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Online Retail Data Analysis]]></title>
            <link>https://medium.com/@seanlukeholland/online-retail-data-analysis-75f3e443828c?source=rss-f5efeadb387a------2</link>
            <guid isPermaLink="false">https://medium.com/p/75f3e443828c</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[tableau]]></category>
            <category><![CDATA[data-vizualisation]]></category>
            <dc:creator><![CDATA[Sean Holland]]></dc:creator>
            <pubDate>Thu, 09 Nov 2023 17:42:09 GMT</pubDate>
            <atom:updated>2023-11-17T17:50:56.128Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*21_U4v2-pccw_beyVQDzAA.png" /></figure><h3>Data Set Overview</h3><p>Just over 541,000 rows of sales data with the following fields:</p><ul><li>InvoiceNo — Unique Identifier under which multiple items can be purchased</li><li>StockCode — Unique Identifier for a product</li><li>Description — Description of the product</li><li>Quantity — Number of product purchased</li><li>InvoiceDate — Date of invoice when purchase was made noted with time of day</li><li>UnitPrice — price per 1 quantity of product</li><li>CustomerId — Unique Identifier for a customer</li><li>Country — Country where product was purchased from</li></ul><h4>Goals</h4><p>Optimize the store’s operations and improve customer satisfaction. Store optimization could include things like inventory management. Given the fields we have to work with this will likely revolve around temporal purchase trends and better understanding outliers. Customer satisfaction might include a deeper understanding of return trends.</p><h4>Focus points for analysis</h4><ul><li>Sales trends</li><li>Customer behavior</li><li>Valuable customers</li><li>Popular products</li></ul><h3><strong>Detect Missing Values</strong></h3><pre>import pandas as pd<br><br># Load the data<br>df = pd.read_excel(&quot;Online Retail.xlsx&quot;, engine=&#39;openpyxl&#39;)<br><br># 1.1 Detecting Missing Values:<br>missing_values = df.isnull().sum()<br>print(&quot;Number of missing values for each column:&quot;)<br>print(missing_values)</pre><pre>Number of missing values for each column:<br>InvoiceNo           0<br>StockCode           0<br>Description      1454<br>Quantity            0<br>InvoiceDate         0<br>UnitPrice           0<br>CustomerID     135080<br>Country             0</pre><p>Altogether there are 541,909 rows of data in this set so the missing descriptions are negligible. However, the <em>missing customer IDs represent almost 25% of the entire data set</em>. Later we’ll do some analysis comparing the unknown with the known customer IDs to better understand if there’s differences in how these groups behave.</p><h3><strong>Outliers</strong></h3><p>Outliers can tell us more about a data set. In this data it’s clear that a majority of sales outliers, calculated as <em>Quantity * UnitPrice, </em>are represented by large negative values (order returns) or fees to Amazon.</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br># Load the data<br>df = pd.read_excel(&quot;Online Retail - No Returns 10.26.23.xlsx&quot;, engine=&#39;openpyxl&#39;)<br><br># Calculate the InterQuartileRange for Sales<br>Q1 = df[&#39;Sales&#39;].quantile(0.25)<br>Q3 = df[&#39;Sales&#39;].quantile(0.75)<br>IQR = Q3 - Q1<br><br># Define bounds for the outliers<br>lower_bound = Q1 - 1.5 * IQR<br>upper_bound = Q3 + 1.5 * IQR<br><br># Identify the outliers<br>outliers_sales = df[(df[&#39;Sales&#39;] &lt; lower_bound) | (df[&#39;Sales&#39;] &gt; upper_bound)]<br><br># Display the outliers<br>print(outliers_sales)<br><br># Plotting the boxplot<br>plt.figure(figsize=(10,6))<br>sns.boxplot(x=df[&#39;Sales&#39;])<br>plt.title(&#39;Boxplot of Sales&#39;)<br>plt.xlabel(&#39;Sales&#39;)<br>plt.show()</pre><pre>InvoiceNo  StockCode                        Description  Quantity  \<br>0        581483      23843        PAPER CRAFT , LITTLE BIRDIE     80995   <br>1        541431      23166     MEDIUM CERAMIC TOP STORAGE JAR     74215   <br>2        556444      22502     PICNIC BASKET WICKER 60 PIECES        60   <br>3        537632  AMAZONFEE                         AMAZON FEE         1   <br>4       A563185          B                    Adjust bad debt         1   <br>...         ...        ...                                ...       ...   <br>42646    540099      82484  WOOD BLACK BOARD ANT WHITE FINISH         6   <br>42647    539826      82484  WOOD BLACK BOARD ANT WHITE FINISH         6   <br>42648    539468      82484  WOOD BLACK BOARD ANT WHITE FINISH         6   <br>42649    539118      82484  WOOD BLACK BOARD ANT WHITE FINISH         6   <br>42650    538660      82484  WOOD BLACK BOARD ANT WHITE FINISH         6   <br><br>              InvoiceDate  UnitPrice  CustomerID         Country      Sales  <br>0     2011-12-09 09:15:00       2.08     16446.0  United Kingdom  168469.60  <br>1     2011-01-18 10:01:00       1.04     12346.0  United Kingdom   77183.60  <br>2     2011-06-10 15:28:00     649.50     15098.0  United Kingdom   38970.00  <br>3     2010-12-07 15:08:00   13541.33         NaN  United Kingdom   13541.33  <br>4     2011-08-12 14:50:00   11062.06         NaN  United Kingdom   11062.06  <br>...                   ...        ...         ...             ...        ...  <br>42646 2011-01-04 16:41:00       6.45     15808.0  United Kingdom      38.70  <br>42647 2010-12-22 12:39:00       6.45     15044.0  United Kingdom      38.70  <br>42648 2010-12-19 13:31:00       6.45     15044.0  United Kingdom      38.70  <br>42649 2010-12-16 11:27:00       6.45     15563.0  United Kingdom      38.70  <br>42650 2010-12-13 15:37:00       6.45     15808.0  United Kingdom      38.70</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*7SHHQ1qktGDXNYoOye7WwQ.png" /><figcaption>(This is not what good work product looks like)</figcaption></figure><p>It’s important to stay humble when evaluating data outside your domain expertise. Analysis of outliers, central tendency and dispersion as well as visualization tools like Tableau are critical in the early stages of analysis to get a feel for the difference between what the data <em>appears </em>to be saying and what it’s actually saying.</p><p>For example, there’s a few quirks with this data set that need to be examined. We already noticed that some of the largest negative sales numbers are related to:</p><ul><li>Amazon fees</li><li>“Manual” (likely a direct accounting adjustment)</li><li>Adjust bad debt (more accounting witchcraft)</li><li>CRUK Commission</li><li>Bank Charges</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*ltLqRpKtplkx9Cwd7hHu6g.png" /><figcaption>All Negative Sales — Includes “Cost of doing business” line items</figcaption></figure><p>And these obscure the data if we’re trying to actually visualize and understand what’s going on with returns. Some questions we might want to answer with respect to returns are:</p><ul><li>Which items have the highest return percentage? Why?</li><li>Which items have the largest negative impact on sales?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*AXWZ9ti0j-mwYFI5wnBeeQ.png" /><figcaption>A filtered list shows us the largest contributors to negative sales (returns)</figcaption></figure><h4><strong>How should we deal with returns in this data set?</strong></h4><p>Let’s explore further:</p><pre>import pandas as pd<br><br># Load the data<br>df = pd.read_excel(&quot;Online Retail.xlsx&quot;, engine=&#39;openpyxl&#39;)<br><br># Calculate Sales if it&#39;s not already present<br>if &#39;Sales&#39; not in df.columns:<br>    df[&#39;Sales&#39;] = df[&#39;Quantity&#39;] * df[&#39;UnitPrice&#39;]<br><br># Keep rows with returns (negative sales)<br>returns = df[df[&#39;Sales&#39;] &lt; 0]<br><br># Filter out the given descriptions<br>filtered_descriptions = [&quot;AMAZON FEE&quot;, &quot;Manual&quot;, &quot;Adjust bad debt&quot;, &quot;CRUK Commission&quot;, &quot;Bank Charges&quot;, &quot;Discount&quot;, &quot;SAMPLES&quot;]<br>returns_filtered = returns[~returns[&#39;Description&#39;].isin(filtered_descriptions)]<br><br># Total sum of sales for all returns<br>total_sales_returned = returns_filtered[&#39;Sales&#39;].sum()<br><br># Top 5 quantities returned and their descriptions<br>top_5_quantities = returns_filtered.groupby(&#39;Description&#39;).sum().sort_values(by=&#39;Quantity&#39;).head(5)[[&#39;Quantity&#39;]]<br><br># Top 5 sales amounts for returns and their descriptions<br>top_5_sales = returns_filtered.groupby(&#39;Description&#39;).sum().sort_values(by=&#39;Sales&#39;).head(5)[[&#39;Sales&#39;]]<br><br>print(f&quot;Total sum of sales for all returns: {total_sales_returned}&quot;)<br>print(&quot;\nTop 5 quantities returned:&quot;)<br>print(top_5_quantities)<br>print(&quot;\nTop 5 sales amounts for returns:&quot;)<br>print(top_5_sales)</pre><pre>Total sum of sales for all returns: -490663.70999999996<br><br>Top 5 quantities returned:<br>                                     Quantity<br>Description                                  <br>PAPER CRAFT , LITTLE BIRDIE            -80995<br>MEDIUM CERAMIC TOP STORAGE JAR         -74494<br>ROTATING SILVER ANGELS T-LIGHT HLDR     -9376<br>FAIRY CAKE FLANNEL ASSORTED COLOUR      -3150<br>PINK BLUE FELT CRAFT TRINKET BOX        -2617<br><br>Top 5 sales amounts for returns:<br>                                        Sales<br>Description                                  <br>PAPER CRAFT , LITTLE BIRDIE        -168469.60<br>MEDIUM CERAMIC TOP STORAGE JAR      -77479.64<br>POSTAGE                             -11871.24<br>REGENCY CAKESTAND 3 TIER             -9722.55<br>WHITE HANGING HEART T-LIGHT HOLDER   -6624.30</pre><blockquote>So there’s about $490,000 worth of sales represented by returns — 4.6% of total sales</blockquote><p>… after controlling for the “Costs of Doing Business” mentioned above. 4.6% is certainly large enough for us to dig deeper into at some point to see if there are any trends worth noting.</p><p>Let’s scale returns by sales:</p><pre>import pandas as pd<br><br># Load the dataset<br>df = pd.read_excel(&quot;Online Retail.xlsx&quot;, engine=&#39;openpyxl&#39;)<br><br># Calculate Sales if it&#39;s not already present<br>if &#39;Sales&#39; not in df.columns:<br>    df[&#39;Sales&#39;] = df[&#39;Quantity&#39;] * df[&#39;UnitPrice&#39;]<br><br># Filter out specific Descriptions<br>filtered_df = df[~df[&#39;Description&#39;].isin([&quot;AMAZON FEE&quot;, &quot;Manual&quot;, &quot;Adjust bad debt&quot;, &quot;CRUK Commission&quot;, &quot;Bank Charges&quot;])]<br><br># Filter out positive sales<br>returns_df = filtered_df[filtered_df[&#39;Sales&#39;] &lt; 0]<br><br># Rank Descriptions by sum of sales<br>ranked_descriptions = returns_df.groupby(&#39;Description&#39;)[&#39;Sales&#39;].sum().sort_values()<br><br># Print bottom 10 Descriptions by sales<br>bottom_descriptions = ranked_descriptions.head(10)<br>print(&quot;Bottom 10 Descriptions by Sales:&quot;)<br>print(bottom_descriptions)<br><br># Calculate the ratio of returns to positive sales<br># First, filter out negative sales from the original dataframe<br>positive_sales_df = filtered_df[filtered_df[&#39;Sales&#39;] &gt; 0]<br><br># Group by Description to get total positive sales for each<br>total_positive_sales = positive_sales_df.groupby(&#39;Description&#39;)[&#39;Sales&#39;].sum()<br><br># Calculate the ratio for the bottom 10 Descriptions<br>ratios = bottom_descriptions.divide(total_positive_sales).dropna().sort_values()<br><br># Print the ratios<br>print(&quot;\nRatios of Returns to Positive Sales for Bottom 10 Descriptions:&quot;)<br>print(ratios)</pre><pre>Bottom 10 Descriptions by Sales:<br>Description<br>PAPER CRAFT , LITTLE BIRDIE          -168469.60<br>MEDIUM CERAMIC TOP STORAGE JAR        -77479.64<br>POSTAGE                               -11871.24<br>REGENCY CAKESTAND 3 TIER               -9722.55<br>WHITE HANGING HEART T-LIGHT HOLDER     -6624.30<br>FAIRY CAKE FLANNEL ASSORTED COLOUR     -6591.42<br>Discount                               -5696.22<br>PANTRY CHOPPING BOARD                  -4803.06<br>DOORMAT FAIRY CAKE                     -4554.90<br>GIN + TONIC DIET METAL SIGN            -3775.33<br>Name: Sales, dtype: float64<br><br>Ratios of Returns to Positive Sales for Bottom 10 Descriptions:<br>Description<br>PAPER CRAFT , LITTLE BIRDIE          -1.000000<br>MEDIUM CERAMIC TOP STORAGE JAR       -0.948333<br>PANTRY CHOPPING BOARD                -0.818448<br>FAIRY CAKE FLANNEL ASSORTED COLOUR   -0.364786<br>DOORMAT FAIRY CAKE                   -0.190671<br>POSTAGE                              -0.151997<br>GIN + TONIC DIET METAL SIGN          -0.146123<br>WHITE HANGING HEART T-LIGHT HOLDER   -0.062321<br>REGENCY CAKESTAND 3 TIER             -0.055721<br>Name: Sales, dtype: float64</pre><blockquote>Sales of PAPER CRAFT, LITTLE BIRDIE were entirely negated by one large return</blockquote><p>For certain parts of our analysis it will make sense to remove returns and for others we’ll keep them. We may also create a subset of negative sales items only to aid our analysis.</p><h3>Summary Statistics</h3><p>A basic overview of the data set to help us find our footing. Let’s remove returns to get a clearer picture as well.</p><pre>import pandas as pd<br><br># Load the data<br>df = pd.read_excel(&quot;Online Retail - No Returns 10.26.23.xlsx&quot;, engine=&#39;openpyxl&#39;)<br><br># Convert the &#39;CustomerID&#39; column to string type<br>df[&#39;CustomerID&#39;] = df[&#39;CustomerID&#39;].astype(str)<br><br># Calculate Sales<br>df[&#39;Sales&#39;] = df[&#39;Quantity&#39;] * df[&#39;UnitPrice&#39;]<br><br># Display basic summary statistics for numeric columns<br>numeric_summary = df.describe()<br><br># Display descriptive summary statistics for non-numeric columns<br>non_numeric_summary = df.describe(include=[&#39;O&#39;])  # &#39;O&#39; stands for object columns, which are typically strings in pandas.<br><br># Display the top 10 rows for inspection<br>top_10_rows = df.head(10)<br><br>print(numeric_summary)<br>print(&quot;\nDescriptive Summary for Non-Numeric Columns:\n&quot;)<br>print(non_numeric_summary)<br>print(&quot;\nTop 10 Rows for Inspection:\n&quot;)<br>print(top_10_rows)</pre><pre>            Quantity      UnitPrice          Sales<br>count  532619.000000  532619.000000  532619.000000<br>mean       10.240006       3.889174      20.026857<br>std       159.593850      35.831786     269.721209<br>min     -9600.000000       0.000000       0.000000<br>25%         1.000000       1.250000       3.750000<br>50%         3.000000       2.080000       9.900000<br>75%        10.000000       4.130000      17.700000<br>max     80995.000000   13541.330000  168469.600000<br><br>Descriptive Summary for Non-Numeric Columns:<br><br>        InvoiceNo StockCode                         Description CustomerID  \<br>count      532619    532619                              531165     532619   <br>unique      22062      4059                                4207       4340   <br>top        573585    85123A  WHITE HANGING HEART T-LIGHT HOLDER        nan   <br>freq         1114      2271                                2327     134695   <br><br>               Country  <br>count           532619  <br>unique              38  <br>top     United Kingdom  <br>freq            487620  <br><br>Top 10 Rows for Inspection:<br><br>  InvoiceNo  StockCode                          Description  Quantity  \<br>0    581483      23843          PAPER CRAFT , LITTLE BIRDIE     80995   <br>1    541431      23166       MEDIUM CERAMIC TOP STORAGE JAR     74215   <br>2    556444      22502       PICNIC BASKET WICKER 60 PIECES        60   <br>3    537632  AMAZONFEE                           AMAZON FEE         1   <br>4   A563185          B                      Adjust bad debt         1   <br>5    551697       POST                              POSTAGE         1   <br>6    567423      23243  SET OF TEA COFFEE SUGAR TINS PANTRY      1412   <br>7    550461      21108   FAIRY CAKE FLANNEL ASSORTED COLOUR      3114   <br>8    540815      21108   FAIRY CAKE FLANNEL ASSORTED COLOUR      3114   <br>9    573003      23084                   RABBIT NIGHT LIGHT      2400   <br><br>          InvoiceDate  UnitPrice CustomerID         Country      Sales  <br>0 2011-12-09 09:15:00       2.08    16446.0  United Kingdom  168469.60  <br>1 2011-01-18 10:01:00       1.04    12346.0  United Kingdom   77183.60  <br>2 2011-06-10 15:28:00     649.50    15098.0  United Kingdom   38970.00  <br>3 2010-12-07 15:08:00   13541.33        nan  United Kingdom   13541.33  <br>4 2011-08-12 14:50:00   11062.06        nan  United Kingdom   11062.06  <br>5 2011-05-03 13:46:00    8142.75    16029.0  United Kingdom    8142.75  <br>6 2011-09-20 11:05:00       5.06    17450.0  United Kingdom    7144.72  <br>7 2011-04-18 13:20:00       2.10    15749.0  United Kingdom    6539.40  <br>8 2011-01-11 12:55:00       2.10    15749.0  United Kingdom    6539.40  <br>9 2011-10-27 12:11:00       2.08    14646.0     Netherlands    4992.00  </pre><blockquote>Average sale amount was ~$20.00 in this data set</blockquote><blockquote><strong>Important Insights:</strong></blockquote><ul><li>Average sale amount was ~$20.00</li><li>There are over 22,000 unique InvoiceNos</li><li>There are over 4,000 unique StockCodes</li><li>The most common CustomerId was N/A and these ~135k represent about 25% of the total data set</li><li>There are 38 unique countries of which the United Kingdom represents over 487,000 rows which is 91.4% of the entire data set!</li></ul><blockquote>The United Kingdom accounts for over $9M in sales or about 85% of total sales</blockquote><p>Let’s first work to better understand the CustomerId = N/A portion of the data set and compare it to known CustomerId data summary statistics.</p><pre>import pandas as pd<br><br># Load the dataset<br>df = pd.read_excel(&quot;Online Retail - No Returns 10.26.23.xlsx&quot;, engine=&#39;openpyxl&#39;)<br><br># Ensure &#39;CustomerID&#39; is treated as a string<br>df[&#39;CustomerID&#39;] = df[&#39;CustomerID&#39;].astype(str)<br><br># Calculate &#39;Sales&#39; column if it&#39;s not already present<br>df[&#39;Sales&#39;] = df[&#39;Quantity&#39;] * df[&#39;UnitPrice&#39;]<br><br># Divide the dataset based on known and unknown &#39;CustomerID&#39;<br>df_known = df[df[&#39;CustomerID&#39;] != &#39;nan&#39;]<br>df_unknown = df[df[&#39;CustomerID&#39;] == &#39;nan&#39;]<br><br># Calculate descriptive statistics for both datasets<br>desc_stats_known = df_known.describe(include=&#39;all&#39;)<br>desc_stats_unknown = df_unknown.describe(include=&#39;all&#39;)<br><br># Print the descriptive statistics in a readable format<br>print(&quot;Descriptive Statistics for Known CustomerID:\n&quot;, &quot;-&quot;*50)<br>print(desc_stats_known)<br>print(&quot;\nDescriptive Statistics for Unknown CustomerID:\n&quot;, &quot;-&quot;*50)<br>print(desc_stats_unknown)</pre><pre>Descriptive Statistics for Known CustomerID:<br> --------------------------------------------------<br>        InvoiceNo StockCode                         Description  \<br>count    397924.0    397924                              397924   <br>unique    18536.0      3665                                3877   <br>top      576339.0    85123A  WHITE HANGING HEART T-LIGHT HOLDER   <br>freq        542.0      2035                                2028   <br>first         NaN       NaN                                 NaN   <br>last          NaN       NaN                                 NaN   <br>mean          NaN       NaN                                 NaN   <br>std           NaN       NaN                                 NaN   <br>min           NaN       NaN                                 NaN   <br>25%           NaN       NaN                                 NaN   <br>50%           NaN       NaN                                 NaN   <br>75%           NaN       NaN                                 NaN   <br>max           NaN       NaN                                 NaN   <br><br>             Quantity          InvoiceDate      UnitPrice CustomerID  \<br>count   397924.000000               397924  397924.000000     397924   <br>unique            NaN                17286            NaN       4339   <br>top               NaN  2011-11-14 15:27:00            NaN    17841.0   <br>freq              NaN                  542            NaN       7847   <br>first             NaN  2010-12-01 08:26:00            NaN        NaN   <br>last              NaN  2011-12-09 12:50:00            NaN        NaN   <br>mean        13.021823                  NaN       3.116174        NaN   <br>std        180.420210                  NaN      22.096788        NaN   <br>min          1.000000                  NaN       0.000000        NaN   <br>25%          2.000000                  NaN       1.250000        NaN   <br>50%          6.000000                  NaN       1.950000        NaN   <br>75%         12.000000                  NaN       3.750000        NaN   <br>max      80995.000000                  NaN    8142.750000        NaN   <br><br>               Country          Sales  <br>count           397924  397924.000000  <br>unique              37            NaN  <br>top     United Kingdom            NaN  <br>freq            354345            NaN  <br>first              NaN            NaN  <br>last               NaN            NaN  <br>mean               NaN      22.394749  <br>std                NaN     309.055588  <br>min                NaN       0.000000  <br>25%                NaN       4.680000  <br>50%                NaN      11.800000  <br>75%                NaN      19.800000  <br>max                NaN  168469.600000  <br><br>Descriptive Statistics for Unknown CustomerID:<br> --------------------------------------------------<br>        InvoiceNo StockCode     Description       Quantity  \<br>count    134695.0    134695          133241  134695.000000   <br>unique     3526.0      3809            3553            NaN   <br>top      573585.0       DOT  DOTCOM POSTAGE            NaN   <br>freq       1114.0       693             692            NaN   <br>first         NaN       NaN             NaN            NaN   <br>last          NaN       NaN             NaN            NaN   <br>mean          NaN       NaN             NaN       2.021797   <br>std           NaN       NaN             NaN      66.783350   <br>min           NaN       NaN             NaN   -9600.000000   <br>25%           NaN       NaN             NaN       1.000000   <br>50%           NaN       NaN             NaN       1.000000   <br>75%           NaN       NaN             NaN       3.000000   <br>max           NaN       NaN             NaN    5568.000000   <br><br>                InvoiceDate      UnitPrice CustomerID         Country  \<br>count                134695  134695.000000     134695          134695   <br>unique                 2980            NaN          1               9   <br>top     2011-10-31 14:41:00            NaN        nan  United Kingdom   <br>freq                   1114            NaN     134695          133275   <br>first   2010-12-01 11:52:00            NaN        NaN             NaN   <br>last    2011-12-09 10:26:00            NaN        NaN             NaN   <br>mean                    NaN       6.172814        NaN             NaN   <br>std                     NaN      60.228821        NaN             NaN   <br>min                     NaN       0.000000        NaN             NaN   <br>25%                     NaN       1.630000        NaN             NaN   <br>50%                     NaN       3.290000        NaN             NaN   <br>75%                     NaN       5.090000        NaN             NaN   <br>max                     NaN   13541.330000        NaN             NaN   <br><br>                Sales  <br>count   134695.000000  <br>unique            NaN  <br>top               NaN  <br>freq              NaN  <br>first             NaN  <br>last              NaN  <br>mean        13.031491  <br>std         73.675498  <br>min          0.000000  <br>25%          2.490000  <br>50%          4.960000  <br>75%         10.790000  <br>max      13541.330000</pre><p><em>Please note the above analysis needs tweaking as we’re applying numerical analysis to discreet data points. Fields like “InvoiceNo”, while technically numerical within the data set, actually represent unique identifiers so calculating the mean for this and StockCode are meaningless.</em></p><blockquote><strong>Important Insights:</strong></blockquote><ul><li>Avg sale for unknown CustomerId is only $13 while known CustomerId is over $22</li><li>Unknown CustomerIds tend to like buying DOTCOM POSTAGE representing 94% of sales for that specific product</li></ul><p>We can also see that unknown CustomerId accounts for a significant chunk of total sales and is much larger than any other single CustomerId.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*-2JqBEf_DjjvA1DyPBtPGw.png" /><figcaption>Unknown CustomerId accounts for over 16% of total sales</figcaption></figure><p>And how about products? Are some more or less associated with unknown CustomerId?</p><pre>import pandas as pd<br><br>df = pd.read_excel(&quot;Online Retail - No Returns 10.26.23.xlsx&quot;, engine=&#39;openpyxl&#39;)<br><br># Calculate the frequencies for each description in both datasets<br>known_freq = df_known[&#39;Description&#39;].value_counts(normalize=True) * 100<br>unknown_freq = df_unknown[&#39;Description&#39;].value_counts(normalize=True) * 100<br><br># Create a DataFrame for comparison<br>percentage_comparison_df = pd.DataFrame({<br>    &#39;Known_Percentage&#39;: known_freq,<br>    &#39;Unknown_Percentage&#39;: unknown_freq<br>})<br><br># Calculate the difference between the two percentages<br>percentage_comparison_df[&#39;Difference&#39;] = percentage_comparison_df[&#39;Known_Percentage&#39;] - percentage_comparison_df[&#39;Unknown_Percentage&#39;]<br><br># Sort by the difference and get the top 10 and bottom 10<br>top_10 = percentage_comparison_df.sort_values(by=&#39;Difference&#39;, ascending=False).head(10)<br>bottom_10 = percentage_comparison_df.sort_values(by=&#39;Difference&#39;).head(10)<br><br># Concatenate the top 10 and bottom 10 for display<br>result_df = pd.concat([top_10, bottom_10])<br><br>print(result_df)</pre><pre>Known_Percentage  Unknown_Percentage  \<br>ASSORTED COLOUR BIRD ORNAMENT               0.353836            0.060792   <br>WHITE HANGING HEART T-LIGHT HOLDER          0.509645            0.224405   <br>POSTAGE                                     0.276183            0.020264   <br>REX CASH+CARRY JUMBO SHOPPER                0.239242            0.009006   <br>REGENCY CAKESTAND 3 TIER                    0.433249            0.221403   <br>BAKING SET 9 PIECE RETROSPOT                0.217881            0.060042   <br>SPOTTY BUNTING                              0.255576            0.107324   <br>HOT WATER BOTTLE KEEP CALM                  0.185965            0.048784   <br>RED HANGING HEART T-LIGHT HOLDER            0.174908            0.048033   <br>LUNCH BAG SPACEBOY DESIGN                   0.253315            0.128339   <br>DOTCOM POSTAGE                              0.004021            0.519360   <br>SUKI  SHOULDER BAG                          0.051517            0.244669   <br>SKULL SHOULDER BAG                          0.035937            0.201890   <br>JUMBO BAG WOODLAND ANIMALS                  0.124898            0.279193   <br>RECYCLING BAG RETROSPOT                     0.104040            0.255927   <br>JUMBO BAG TOYS                              0.062072            0.208644   <br>BEADED CRYSTAL HEART PINK ON STICK          0.003016            0.145601   <br>CHARLIE+LOLA PINK HOT WATER BOTTLE          0.027141            0.156108   <br>VINTAGE PAISLEY STATIONERY SET              0.054282            0.177873   <br>JUMBO BAG CHARLIE AND LOLA TOYS             0.027392            0.144100   <br><br>                                    Difference  <br>ASSORTED COLOUR BIRD ORNAMENT         0.293044  <br>WHITE HANGING HEART T-LIGHT HOLDER    0.285240  <br>POSTAGE                               0.255919  <br>REX CASH+CARRY JUMBO SHOPPER          0.230235  <br>REGENCY CAKESTAND 3 TIER              0.211845  <br>BAKING SET 9 PIECE RETROSPOT          0.157839  <br>SPOTTY BUNTING                        0.148252  <br>HOT WATER BOTTLE KEEP CALM            0.137181  <br>RED HANGING HEART T-LIGHT HOLDER      0.126875  <br>LUNCH BAG SPACEBOY DESIGN             0.124976  <br>DOTCOM POSTAGE                       -0.515339  <br>SUKI  SHOULDER BAG                   -0.193152  <br>SKULL SHOULDER BAG                   -0.165953  <br>JUMBO BAG WOODLAND ANIMALS           -0.154295  <br>RECYCLING BAG RETROSPOT              -0.151887  <br>JUMBO BAG TOYS                       -0.146572  <br>BEADED CRYSTAL HEART PINK ON STICK   -0.142585  <br>CHARLIE+LOLA PINK HOT WATER BOTTLE   -0.128967  <br>VINTAGE PAISLEY STATIONERY SET       -0.123591  <br>JUMBO BAG CHARLIE AND LOLA TOYS      -0.116708</pre><p>So above we’re calculating how often certain products appear in the known vs unknown data sets, standardizing it by scaling appearances against its respective whole, and then comparing the two. In the context of how we set up this specific analysis, this means:</p><ul><li>A difference of +1 would mean a product is <em>only </em>purchased by known CustomerIds</li><li>A difference of -1 would mean a product is <em>only </em>purchased by unknown CustomerIds</li></ul><p>Therefore the following tend to be more likely to be purchased by known CustomerIds:</p><ul><li>ASSORTED COLOUR BIRD ORNAMENT</li><li>WHITE HANGING HEART T-LIGHT HOLDER</li><li>POSTAGE</li></ul><blockquote>… and one product stands head and shoulders above the rest as being purchased mostly by unknown CustomerIds:</blockquote><blockquote>DOTCOM POSTAGE</blockquote><p>Let’s isolate these products for a moment and see them visually to compare with each other as well as in the context of overall sales.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B28EHRYN1ZbaE3HGkua-ow.png" /></figure><p>The products above represent the most popular products as measured by total sales, especially DOTCOM POSTAGE. This begs the question:</p><ul><li>Why do unknown CustomerIds buy so much dotcom postage?</li></ul><p>We’ll ponder this while we uncover more insights.</p><h3>MOST POPULAR PRODUCTS BY SALES</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UZnw7qX0QpPuLohcPfIIJw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xIg9a5rWlAzQKXxfWpWhYg.png" /></figure><p>Above we have the top ten products by total sales and below I’ve compared them in aggregate against total sales. Note “Manual” is likely an accounting adjustment.</p><blockquote>DOTCOM POSTAGE is the number one product in the data set by sales</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*vOS4F-iBub395S-_5jwl6A.png" /><figcaption>The top 10 products make up almost 11% of total sales</figcaption></figure><p>Since we know the UK (in pink below) represents over 91% of the data set, we’d expect most of these sales are from the United Kingdom.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b_pL0JsblYlSnv3TsaGchw.png" /><figcaption>UK (Pink) Represents majority of sales</figcaption></figure><p>We know from earlier analysis that there are 4340 unique CustomerIds but about 25% of the entire data set is represented by unknown CustomerId. In the top ten products we can see those represented here in the dark blue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*28SVaogTAONzeWw7OI1kSw.png" /><figcaption>Unknown CustomerId (dark blue) makes up a large portion of the top 10 products</figcaption></figure><p>Interestingly, CustomerId 16446 (red) makes up the entirety of the 3rd highest grossing product. They definitely enjoy their PAPER CRAFT, LITTLE BIRDIE… Whatever that is.</p><p>In fact, unknown CustomerId is overrepresented in the top 30 products as measured by sales by quite a wide margin. We’ll aggregate all known CustomerIds into gray to make this visually obvious.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i5FdBTb_u2tNYIMaxDz7gA.png" /><figcaption>Unknown CustomerIds in blue</figcaption></figure><h3>CUSTOMER PROFILES</h3><p>Speaking of CustomerId, which customers are the most valuable in terms of sales? Here are the top ten compared with one another:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*cKPMeqWD7qPCf4WrcmrKHg.png" /><figcaption>Unknown CustomerId in Blue — greater than 50% of the top 10</figcaption></figure><p>Setting aside unknown CustomerId (blue) for the moment, there are a few other customers we may want to analyze further as noted in the above pie chart. We’ll have recommendations for management on these at the end.</p><h4>And how much of the total sales do the top ten CustomerIds represent?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*kimsohcqE9LIaKZF6MaXJA.png" /><figcaption>Top 10 CustomerIds (blue) make up over 30% of total sales</figcaption></figure><p>So these are customers we may want to diver deeper on — especially the UnknownIds.</p><p>Let’s bring python back into the mix to find the total sales for the top five CustomerIds.</p><pre>import pandas as pd<br><br># Load the dataset<br>df = pd.read_excel(&quot;Online Retail - No Returns 10.26.23.xlsx&quot;, engine=&#39;openpyxl&#39;)<br><br># List of top 5 CustomerIDs by sales<br>top_customer_ids = [18102, 17450, 16446, 14646, None]<br><br># Filter the dataframe to only include these CustomerIDs<br>top_customers = df[df[&#39;CustomerID&#39;].isin(top_customer_ids)]<br><br># Replace NaN values with a placeholder<br>top_customers[&#39;CustomerID&#39;].fillna(&#39;Unknown&#39;, inplace=True)<br><br># Calculate total sales for each of these CustomerIDs<br>total_sales_per_customer = top_customers.groupby(&#39;CustomerID&#39;)[&#39;Sales&#39;].sum().sort_values(ascending=False)<br><br># Print results with formatted values<br>for customer, sales in total_sales_per_customer.items():<br>    print(f&quot;CustomerID: {customer}, Total Sales: ${sales:,.2f}&quot;)</pre><pre>CustomerID: Unknown, Total Sales: $1,755,276.64<br>CustomerID: 14646.0, Total Sales: $280,206.02<br>CustomerID: 18102.0, Total Sales: $259,657.30<br>CustomerID: 17450.0, Total Sales: $194,550.79<br>CustomerID: 16446.0, Total Sales: $168,472.50</pre><p>And which are the most popular products with our top consumers?</p><pre>import pandas as pd<br><br># Load the dataset<br>df = pd.read_excel(&quot;Online Retail - No Returns 10.26.23.xlsx&quot;, engine=&#39;openpyxl&#39;)<br><br># List of top 5 CustomerIDs by sales<br>top_customer_ids = [18102, 17450, 16446, 14646, None]<br><br># For each CustomerID, find the top 3 products by sales and their respective percentages<br>for customer_id in top_customer_ids:<br>    if customer_id is None:<br>        customer_df = df[df[&#39;CustomerID&#39;].isna()]<br>    else:<br>        customer_df = df[df[&#39;CustomerID&#39;] == customer_id]<br>    <br>    # Calculate total sales for this customer<br>    total_sales = customer_df[&#39;Sales&#39;].sum()<br>    <br>    # Group by Description and sum sales, then sort and get top 3 products<br>    top_products = customer_df.groupby(&#39;Description&#39;).agg({&#39;Sales&#39;: &#39;sum&#39;}).sort_values(by=&#39;Sales&#39;, ascending=False).head(3)<br>    <br>    # Calculate the percentage of total sales for each product<br>    top_products[&#39;Percentage of Total Sales&#39;] = (top_products[&#39;Sales&#39;] / total_sales) * 100<br>    <br>    # Print the results<br>    print(f&quot;CustomerID: {customer_id if customer_id is not None else &#39;Unknown&#39;}&quot;)<br>    print(top_products)<br>    print(&quot;\n&quot; + &quot;-&quot;*50 + &quot;\n&quot;)</pre><pre>CustomerID: 18102<br>                                      Sales            % of Total Sales<br>Description                                                           <br>VINTAGE UNION JACK MEMOBOARD       16592.08                   6.389992<br>WOOD BLACK BOARD ANT WHITE FINISH  15351.00                   5.912023<br>CREAM HEART CARD HOLDER            14089.90                   5.426345<br><br>--------------------------------------------------<br><br>CustomerID: 17450<br>                                        Sales          % of Total Sales<br>Description                                                             <br>HEART OF WICKER LARGE                13459.64                   6.918317<br>WHITE HANGING HEART T-LIGHT HOLDER   13253.84                   6.812535<br>SET OF TEA COFFEE SUGAR TINS PANTRY  10566.73                   5.431348<br><br>--------------------------------------------------<br><br>CustomerID: 16446<br>                                 Sales                % of Total Sales<br>Description                                                      <br>PAPER CRAFT , LITTLE BIRDIE  168469.60                  99.998279<br>PANTRY SCRUBBING BRUSH            1.65                   0.000979<br>PANTRY PASTRY BRUSH               1.25                   0.000742<br><br>--------------------------------------------------<br><br>CustomerID: 14646<br>                                       Sales          % of Total Sales<br>Description                                                            <br>RABBIT NIGHT LIGHT                   9568.48                   3.414802<br>ROUND SNACK BOXES SET OF4 WOODLAND   7956.00                   2.839339<br>SPACEBOY LUNCH BOX                   7415.40                   2.646410<br><br>--------------------------------------------------<br><br>CustomerID: Unknown<br>                              Sales                   % of Total Sales<br>Description                                                   <br>DOTCOM POSTAGE            194342.41                  11.071896<br>REGENCY CAKESTAND 3 TIER   31891.79                   1.816910<br>PARTY BUNTING              30660.00                   1.746733<br><br>--------------------------------------------------</pre><p><strong>Two things jump off the page here:</strong></p><ul><li>99.99% of 16446’s sales were PAPER CRAFT, LITTLE BIRDIE</li><li>11% of Unknown CustomerId’s sales were DOTCOM POSTAGE</li></ul><h3>TEMPORAL TRENDS</h3><p>What do sales look like over the course of the year?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rs167vO_RUU9xtI1Kil3Vw.png" /><figcaption>UK noted in pink — a majority of sales</figcaption></figure><p>There’s a predictable run up in sales leading into the holiday season. Notably the UK becomes an even larger majority of sales during this time.</p><p><strong>What about our top 10 products over time?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TRsjNpW7OT8J74CFzMCXDQ.png" /></figure><blockquote><strong>Important Insights:</strong></blockquote><ul><li>ALL sales of PAPER CRAFT, LITTLE BIRDIE were from December</li><li>95% of MEDIUM CERAMIC TOP STORAGE JAR were purchased in January</li></ul><p>At this point we have a lot of good insights to start drawing some conclusions and build a case for taking certain business actions to <strong>optimize store operations. </strong>Some of these actions may also help improve customer satisfaction.</p><p>However, we need to dig deeper into returns to explore whether this is linked with any of the trends we’ve already discovered.</p><h3>RETURNS ANALYSIS</h3><p>Let’s start by ranking returns by sales after filtering out our “costs of doing business”.</p><pre>import pandas as pd<br><br># Load the dataset<br>df = pd.read_excel(&quot;Online Retail.xlsx&quot;, engine=&#39;openpyxl&#39;)<br><br># Calculate Sales if it&#39;s not already present<br>if &#39;Sales&#39; not in df.columns:<br>    df[&#39;Sales&#39;] = df[&#39;Quantity&#39;] * df[&#39;UnitPrice&#39;]<br><br># Filter out specific Descriptions<br>filtered_df = df[~df[&#39;Description&#39;].isin([&quot;AMAZON FEE&quot;, &quot;Manual&quot;, &quot;Adjust bad debt&quot;, &quot;CRUK Commission&quot;, &quot;Bank Charges&quot;])]<br><br># Filter out positive sales<br>returns_df = filtered_df[filtered_df[&#39;Sales&#39;] &lt; 0]<br><br># Rank Descriptions by sum of sales<br>ranked_descriptions = returns_df.groupby(&#39;Description&#39;)[&#39;Sales&#39;].sum().sort_values()<br><br># Print bottom 10 Descriptions by sales<br>bottom_descriptions = ranked_descriptions.head(10)<br>print(&quot;Bottom 10 Descriptions by Sales:&quot;)<br>print(bottom_descriptions)<br><br># Calculate the ratio of returns to positive sales<br># First, filter out negative sales from the original dataframe<br>positive_sales_df = filtered_df[filtered_df[&#39;Sales&#39;] &gt; 0]<br><br># Group by Description to get total positive sales for each<br>total_positive_sales = positive_sales_df.groupby(&#39;Description&#39;)[&#39;Sales&#39;].sum()<br><br># Calculate the ratio for the bottom 10 Descriptions<br>ratios = bottom_descriptions.divide(total_positive_sales).dropna().sort_values()<br><br># Print the ratios<br>print(&quot;\nRatios of Returns to Positive Sales for Bottom 10 Descriptions:&quot;)<br>print(ratios)</pre><pre>Bottom 10 Descriptions by Sales:<br>Description<br>PAPER CRAFT , LITTLE BIRDIE          -168469.60<br>MEDIUM CERAMIC TOP STORAGE JAR        -77479.64<br>POSTAGE                               -11871.24<br>REGENCY CAKESTAND 3 TIER               -9722.55<br>WHITE HANGING HEART T-LIGHT HOLDER     -6624.30<br>FAIRY CAKE FLANNEL ASSORTED COLOUR     -6591.42<br>Discount                               -5696.22<br>PANTRY CHOPPING BOARD                  -4803.06<br>DOORMAT FAIRY CAKE                     -4554.90<br>GIN + TONIC DIET METAL SIGN            -3775.33<br>Name: Sales, dtype: float64<br><br>Ratios of Returns to Positive Sales for Bottom 10 Descriptions:<br>Description<br>PAPER CRAFT , LITTLE BIRDIE          -1.000000<br>MEDIUM CERAMIC TOP STORAGE JAR       -0.948333<br>PANTRY CHOPPING BOARD                -0.818448<br>FAIRY CAKE FLANNEL ASSORTED COLOUR   -0.364786<br>DOORMAT FAIRY CAKE                   -0.190671<br>POSTAGE                              -0.151997<br>GIN + TONIC DIET METAL SIGN          -0.146123<br>WHITE HANGING HEART T-LIGHT HOLDER   -0.062321<br>REGENCY CAKESTAND 3 TIER             -0.055721<br>Name: Sales, dtype: float64</pre><blockquote><strong>Important insights:</strong></blockquote><ul><li>PAPER CRAFT, LITTLE BIRDIE was completely negated by returns. Recall from earlier this was the 3rd highest grossing product by sales</li><li>MEDIUM CERAMIC TOP STORAGE JAR had almost a 95% return rate and note from earlier that 95% of all annual sales come in the month of January</li><li>PANTRY CHOPPING BOARD had an 82% return rate</li></ul><p>Another way to come at this is by starting with the highest return ratio items to see if there’s anything interesting to uncover there.</p><pre>import pandas as pd<br><br># Load the data<br>df = pd.read_excel(&quot;Online Retail.xlsx&quot;, engine=&#39;openpyxl&#39;)<br><br># Calculate Sales if it&#39;s not already present<br>if &#39;Sales&#39; not in df.columns:<br>    df[&#39;Sales&#39;] = df[&#39;Quantity&#39;] * df[&#39;UnitPrice&#39;]<br><br># Filter out specific Descriptions<br>filtered_df = df[~df[&#39;Description&#39;].isin([&quot;AMAZON FEE&quot;, &quot;Manual&quot;, &quot;Adjust bad debt&quot;, &quot;CRUK Commission&quot;, &quot;SAMPLES&quot;, &quot;Bank Charges&quot;])]<br><br># Filter out positive sales for the returns dataframe<br>returns_df = filtered_df[filtered_df[&#39;Sales&#39;] &lt; 0]<br><br># Rank Descriptions by sum of sales for returns<br>ranked_returns = returns_df.groupby(&#39;Description&#39;)[&#39;Sales&#39;].sum().sort_values()<br><br># Filter out negative sales from the original dataframe for positive sales<br>positive_sales_df = filtered_df[filtered_df[&#39;Sales&#39;] &gt; 0]<br><br># Group by Description to get total positive sales for each<br>total_positive_sales = positive_sales_df.groupby(&#39;Description&#39;)[&#39;Sales&#39;].sum()<br><br># Calculate the ratio of returns to positive sales for each Description<br>ratios = ranked_returns.divide(total_positive_sales).dropna().sort_values()<br><br># Create a DataFrame with the return sales amount, positive sales amount, and the ratios<br>summary_df = pd.DataFrame({<br>    &#39;Return Sales&#39;: ranked_returns,<br>    &#39;Positive Sales&#39;: total_positive_sales,<br>    &#39;Ratio&#39;: ratios<br>})<br><br># Print bottom 10 Descriptions ranked by ratio<br>bottom_ratios = summary_df.sort_values(by=&#39;Ratio&#39;).head(10)<br>print(&quot;Bottom 10 Descriptions by Return to Sales Ratio:&quot;)<br>print(bottom_ratios)</pre><pre>Bottom 10 Descriptions by Return to Sales Ratio:<br>                                     Return Sales  Positive Sales     Ratio<br>BLUE PADDED SOFT MOBILE                    -29.75            4.25 -7.000000<br>PINK CHERRY LIGHTS                         -54.00           27.00 -2.000000<br>WOODEN BOX ADVENT CALENDAR                -135.20           89.50 -1.510615<br>PINK SMALL GLASS CAKE STAND                -52.65           46.80 -1.125000<br>ROBIN CHRISTMAS CARD                        -5.04            5.02 -1.003984<br>BLACK CHERRY LIGHTS                        -54.00           54.00 -1.000000<br>GLASS CAKE COVER AND PLATE                 -29.90           29.90 -1.000000<br>PAPER CRAFT , LITTLE BIRDIE            -168469.60       168469.60 -1.000000<br>HANGING RIDGE GLASS T-LIGHT HOLDER         -60.84           60.84 -1.000000<br>WHITE BEADED GARLAND STRING 20LIGHT        -18.25           19.05 -0.958005</pre><p>We can see here that none of these items has very meaningful sales aside from PAPER CRAFT so we won’t focus on these.</p><p>Let’s make it visually obvious which products have the largest returns compared to their sales.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ml-wQxPpeO9bZJlNQPTZCw.png" /><figcaption>Returns (Red) vs Sales (Blue)</figcaption></figure><p>Based on the sales numbers, it would be important to better understand and focus on improving returns for some of these products and we’ll include those in our recommendations for management.</p><h3>Recommendations for Management</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u_6fXPU-FCeOdDmEoB_8VQ.png" /></figure><p>We’ll summarize our insights through the lens of our original focus points mentioned at the beginning of our data deep dive.</p><h4>Sales trends</h4><p>Given the large spike in sales starting in November and lasting through January, management should make appropriate adjustments to supply chain schedules and inventory management techniques to accommodate this.</p><h4>Customer behavior</h4><p>Given the large spikes in customer returns during April, August and October through December, it makes sense to increase customer support staff and/or expand hours and capabilities for customer support to increase customer satisfaction.</p><h4>Valuable customers</h4><p>The vast majority of purchases and sales come from UK customers. This applies relatively evenly to most of the top selling products and certainly the top 10 products.</p><p>Unknown CustomerId needs further analysis to better understand if this is a single customer, a few customers or many customers as it represents such a large percentage of overall sales. Since this individual (or group) is the vast majority of the best-selling product, DOTCOM POSTAGE, it’s critical to understand this customer better.</p><p>As for specific valuable CustomerIds here they are ranked by sales excluding Unknown:</p><ol><li>14646 — $280,000</li><li>18102 — $260,000</li><li>17450 — $194,000</li><li>16446 — $168,000 (all negated by returns)</li><li>14911 — $144,000</li></ol><p>Other notable large-sale customers are noted here for unique purchase behavior:</p><p>15098 — $40,000 spent entirely on PICNIC BASKET WICKER 60 PIECES. Coordination directly with this buyer may entice other purchases.</p><p>Management may want to consider offering loyalty programs or discounts to these specific CustomerIds.</p><h4>Popular products</h4><p>As noted above, the top 10 products (out of ~4200) represent over 10% of sales and so management should make sure these are properly stocked and marketed. We’ll touch on some of the top 10 here starting with the highest-grossing and therefore most in-demand products.</p><p>DOTCOM POSTAGE — we need to better understand why our top-selling product is almost entirely bought by unknown CustomerIds. Helpfully, we do know the majority of these reside in the UK which aligns with the rest of our insights and should benefit from our earlier customer service recommendations for aligning customer service hours during UK work hours.</p><p>REGENCY CAKESTAND 3 TIER — sales of this product are remarkably steady throughout the year with a noticeable 2–3x December jump.</p><p>PAPER CRAFT, LITTLE BIRDIE — our 3rd highest selling product had it’s one extremely large sale entirely negated almost immediately by a very large return. This is hard to interpret and I’d rely on domain experts for more insight. My guess would be this is a recalled or otherwise defective product that was issued a full refund.</p><p>WHITE HANGING HEART T-LIGHT HOLDER, PARTY BUNTING and JUMBO BAG RED RETROSPOT 4th, 5th and 6th on the list of highest-sale products and should be properly stocked for holiday season demand jumps with the exception of PARTY BUNTING which jumps during late Spring and early Summer.</p><p>MEDIUM CERAMIC TOP STORAGE JAR — another product that had over 95% of it’s sales negated by one large return. Likely another defective product or recall scenario. I’d solicit management domain experts for further interpretation.</p><h3>EARLY RETROSPECTIVE</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qtl1dg5mFoUizMV80PZSSg.png" /></figure><p>This ended up taking significantly longer than anticipated. Like most large data sets, if we’re not a domain expert we end up going down some paths we think are useful only to find that we need to retrace our steps and take a different perspective.</p><blockquote>Properly tracking the changes and modifications to the data and subsets of data we’re analyzing is <em>extremely </em>important, not only for ourselves but for the inevitable questions that management will have.</blockquote><blockquote><strong>DATA TRACKING</strong></blockquote><ul><li>Any new python code needs to be properly commented and labelled with markdown</li><li>All tableau visualizations need to be labelled</li><li>Old visualizations need to be discarded to eliminate clutter to keep the most important data in our crosshairs</li><li>Saved data subsets should be properly labelled, ideally with today’s date so it can form a breadcrumb trail in time</li><li>Never modify the original data set, always start with a separate file</li><li>Keep track of which data sets are loaded into tableau and which files are being loaded into Pandas dataframes. Always confirm you’re comparing apples to apples and not accidentally comparing different data sets or subsets</li></ul><blockquote><strong>OUTLIERS</strong></blockquote><p>After analyzing and pinpointing outliers it’s valuable to isolate these and visualize them in tableau as well as excel. Python and tableau are usually good starting points to identify these outliers but they are not as easy or as intuitive as a quick excel filter to understand what’s actually happening. <em>Using all three tools in tandem is powerful.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75f3e443828c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Quest for the Perfect Beer]]></title>
            <link>https://medium.com/@seanlukeholland/the-quest-for-the-perfect-beer-ccc698697d58?source=rss-f5efeadb387a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccc698697d58</guid>
            <category><![CDATA[tableau]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[beer]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Sean Holland]]></dc:creator>
            <pubDate>Mon, 06 Nov 2023 15:13:31 GMT</pubDate>
            <atom:updated>2026-10-13T14:44:39.499Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NZLsuSyYEJ3iKNo9Fx8Vng.png" /><figcaption>Midjourney Beer!</figcaption></figure><p>This data set contained about 530,000 beer reviews spread across 103 different beer styles. My mission was to:</p><ol><li>Find the perfect beer</li><li>Create a useful dashboard for beer lovers to find new beers they like</li><li>Answer some specific questions regarding the data</li></ol><h3>Data Transformation — Cleaning &amp; Additions</h3><p>The original file was a tar.bz2 file and I wanted to get this into a CSV format in order to be able to analyze it with python and load it into tableau.</p><pre>import pandas as pd<br><br># Source data: BeerAdvocate reviews, distributed as a bz2-compressed archive<br>SOURCE = &quot;BeerDataScienceProject.tar.bz2&quot;<br>OUTPUT = &quot;BeerDataScienceProject.csv&quot;<br><br># Load the compressed CSV directly into a dataframe<br>df = pd.read_csv(SOURCE, compression=&quot;bz2&quot;)<br><br># Write out an uncompressed CSV for analysis in Python and Tableau<br>print(f&quot;Saving data to {OUTPUT}...&quot;)<br>df.to_csv(OUTPUT, index=False)<br>print(f&quot;Data saved to {OUTPUT}&quot;)</pre><p>Next the review_time column needed to be converted into something human readable:</p><pre>import pandas as pd<br><br>CSV = &quot;BeerDataScienceProject.csv&quot;<br><br>df = pd.read_csv(CSV)<br><br># review_time arrives as a Unix epoch integer; convert to datetime<br>df[&quot;review_time&quot;] = pd.to_datetime(df[&quot;review_time&quot;], unit=&quot;s&quot;)<br><br>df.to_csv(CSV, index=False)</pre><h3>Analysis</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MUXpsCuuBer05JiGVgyO7w.png" /><figcaption>Highest average ABV — filtered by minimum # reviews</figcaption></figure><h4><strong>RANK THE TOP 3 BREWERIES THAT PRODUCE THE STRONGEST BEERS</strong></h4><p>Breweries had to be extrapolated by combining the brewer ID# with the name of the beers. On an absolute basis they were as follows:</p><ol><li>6513 — SchorschbrÃ¤u — 19.23% ABV</li><li>736 — Samichlaus — 13.75% ABV</li><li>24215 — BrÃderna Andersson — 12.47% ABV</li></ol><p>However these accounted for quite a small number of overall reviews so I put a lower bound on number of reviews at a minimum ~.75% of reviews and got the following:</p><ol><li>207 — Rochefort — 9.93% ABV</li><li>16866 — The Bruery — 9.51% ABV</li><li>396 — AleSmith — 9.39% ABV</li></ol><h4>WHICH YEAR DID BEERS HAVE THE OVERALL HIGHEST RATINGS?</h4><p>Easy enough: 2000 had an average overall beer rating of 4.18 / 5.00. Remember this data set is from 1998–2012</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aOFgsSAbI8Oz9he-JY5PTg.png" /></figure><h4>WHAT IS THE MOST IMPORTANT ASPECT OF A BEER BASED ON USER RATINGS?</h4><p>Users have four review categories with which to judge beers:</p><ul><li>Appearance</li><li>Aroma</li><li>Palette</li><li>Taste</li></ul><p>Users left ratings between 1–5 for each of these and then gave an overall rating between 1–5. This question was asked <em>specifically with respect to users’ ratings</em>. Given this guidance, I started with regression analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*agurWoOvaV-9fSPm6dkeMw.png" /></figure><p>P-values were less than .0001 and we can see visually there’s a positive relationship between all categories and overall rating.</p><p><strong>R-squared values</strong></p><ul><li>Appearance — 38%</li><li>Aroma — 76%</li><li>Palette — 56%</li><li>Taste — 66%</li></ul><p>So these would indicate that Aroma and Taste would be the strongest predictors of overall rating. I then did a linear regression analysis using all categories simultaneously in the model in python:</p><pre>import pandas as pd<br>import statsmodels.formula.api as smf<br>from scipy import stats<br><br>df = pd.read_csv(&quot;BeerDataScienceProject.csv&quot;)<br><br># Model overall rating as a function of the four component scores<br>formula = &quot;review_overall ~ review_appearance + review_aroma + review_palette + review_taste&quot;<br>results = smf.ols(formula=formula, data=df).fit()<br><br>print(results.summary())<br><br># Residual diagnostics<br>residuals = results.resid<br>print(&quot;Residuals mean:&quot;, residuals.mean())<br>print(&quot;Residuals variance:&quot;, residuals.var())<br><br>k2, p = stats.normaltest(residuals.dropna())<br>print(&quot;Normality test p-value:&quot;, p)<br><br></pre><p>With the following results:</p><pre>OLS Regression Results                            <br>==============================================================================<br>Dep. Variable:         review_overall   R-squared:                       0.648<br>Model:                            OLS   Adj. R-squared:                  0.648<br>Method:                 Least Squares   F-statistic:                 2.430e+05<br>Date:                Fri, 30 Jun 2023   Prob (F-statistic):               0.00<br>Time:                        12:42:11   Log-Likelihood:            -2.9348e+05<br>No. Observations:              528870   AIC:                         5.870e+05<br>Df Residuals:                  528865   BIC:                         5.870e+05<br>Df Model:                           4                                         <br>Covariance Type:            nonrobust                                         <br>=====================================================================================<br>                        coef    std err          t      P&gt;|t|      [0.025      0.975]<br>-------------------------------------------------------------------------------------<br>Intercept             0.4483      0.004    109.066      0.000       0.440       0.456<br>review_appearance     0.0330      0.001     27.027      0.000       0.031       0.035<br>review_aroma          0.5531      0.001    410.553      0.000       0.550       0.556<br>review_palette        0.0449      0.001     35.813      0.000       0.042       0.047<br>review_taste          0.2594      0.001    196.120      0.000       0.257       0.262<br>==============================================================================<br>Omnibus:                    26519.537   Durbin-Watson:                   1.778<br>Prob(Omnibus):                  0.000   Jarque-Bera (JB):            94405.140<br>Skew:                          -0.124   Prob(JB):                         0.00<br>Kurtosis:                       5.055   Cond. No.                         55.7<br>==============================================================================<br><br>Notes:<br>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.<br>Residuals mean: -9.972130814028396e-15<br>Residuals variance: 0.17762997147390264<br>Normality test p-value: 0.0<br>The residuals may not be normally distributed.</pre><p>With a <strong>coefficient of .55 this would indicate aroma has the strongest relationship with overall review rating</strong> BUT we note that the residuals may not be normally distributed so we test for collinearity using the Variance Inflation Factor (VIF) method:</p><pre>import pandas as pd<br>from statsmodels.stats.outliers_influence import variance_inflation_factor<br><br><br># Path to the tar.bz2 file<br>tar_bz2_file = r&quot;C:\REDACTED\BeerDataScienceProject.tar.bz2&quot;<br><br># Load the compressed CSV into a pandas dataframe<br>df = pd.read_csv(tar_bz2_file, compression=&#39;bz2&#39;)<br><br># Now df holds your data<br>print(df.head())<br><br># Print the number of rows<br>num_rows = len(df)<br>print(f&quot;The DataFrame has {num_rows} rows.&quot;)<br><br># Print the number of columns<br>num_cols = len(df.columns)<br>print(f&quot;The DataFrame has {num_cols} columns.&quot;)<br>print(df.columns)<br><br># Change the pandas display options<br>pd.set_option(&#39;display.max_columns&#39;, None)<br><br># Calculate the correlation matrix<br>corr_matrix = df[[&#39;review_appearance&#39;, &#39;review_palette&#39;, &#39;review_overall&#39;, &#39;review_taste&#39;, &#39;review_aroma&#39;]].corr()<br><br>print(corr_matrix)<br>print()<br><br><br># Create a new DataFrame with the columns you&#39;re interested in<br>df_vif = df[[&#39;review_appearance&#39;, &#39;review_palette&#39;, &#39;review_overall&#39;, &#39;review_taste&#39;, &#39;review_aroma&#39;]].dropna()<br><br><br># For each column, calculate VIF and print it<br>for i in range(len(df_vif.columns)):<br>    vif = variance_inflation_factor(df_vif.values, i)<br>    print(f&quot;VIF for {df_vif.columns[i]}: {vif}&quot;)<br><br></pre><p>If we see VIF values &gt; 10 collinearity is likely present:</p><pre>VIF for review_appearance: 54.66400901796027<br>VIF for review_palette: 66.97704453414977<br>VIF for review_overall: 83.67487573006062<br>VIF for review_taste: 80.26988537152171<br>VIF for review_aroma: 107.3713455858943</pre><p>So while aroma seems to be a good indicator we have to take that with a grain of salt. The next question is a great one to combine with our previous analysis to better understand which categories are most important to consumers and which are most likely to affect overall rating.</p><h3><strong>FAVORITE BEER STYLE BASED ON USER REVIEWS</strong></h3><p><strong>And: How do written reviews compare to overall review score for the beer style?</strong></p><p>For this we needed to use an NLTK (natural language tool kit) to perform sentiment analysis on all the reviews to assign a rating from -1 (highly negative to +1 (high positive). This required several iterations to figure out the best combination of libraries to balance accuracy and speed.</p><p>First I tried Textblob in combination with the NLTK library, pandas and string but the speed was untenable.</p><p>I then discarded Textblob for Flair and introduced multiprocessing in order to utilize all four of my laptop cores which could theoretically reduce process time by a factor of 4. However, Flair is, as of this writing, one of the most advanced natural language processing models available to retail users and introduced enough complexity to slow the process down way too much. Again, untenable.</p><p>Last I tried VADER (Valence Aware Dictionary for Sentiment Reasoning), a rule-based (simpler) model often used for social media and shorter blocks of sentiment like twitter posts (max 280 characters). This, combined with multiprocessing was able to assign reasonably accurate results when sorting and spot-checking the data in excel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H_iq5czxR_jkRz8E_7KYkg.png" /><figcaption>Sentiment Analysis — Pure</figcaption></figure><blockquote>Based on pure sentiment analysis, the top three beers with the most positive sentiment were:</blockquote><blockquote>Happoshu — .8452</blockquote><blockquote>Eisbock — .8164</blockquote><blockquote>Roggenbier — .8009</blockquote><p>However, in order to alleviate error from the sentiment score model, I felt it was appropriate to weight these by overall review ranking (1–5 scale).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lDhIrMqzpQoiIJyLPp3prw.png" /><figcaption>Sentiment Analysis — Weighted by Rank</figcaption></figure><p>This gave different results without the huge clustering in the .76 — .78 range given by the pure sentiment analysis:</p><ol><li>Eisbock — 3.33</li><li>Roggenbier — 3.23</li><li>Berliner Weissbier — 3.225</li></ol><p>This was all well and good but I wanted to create something consumers would actually find useful which gave birth to the following dashboard:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U4du16wnq2mdWt65G7HKng.png" /></figure><h3>BEER COMPARISON — FIND YOUR NEW FAVORITE BEER</h3><p>The idea was to give users a way to:</p><ul><li>Compare multiple beers against each other</li><li>Find beers similar to the ones a user already likes</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IZLwVFwpT0im90vNDm9edg.png" /></figure><p>The top left tree chart on this dashboard (Where it says “START”) is meant to be the starting point for beer comparisons. Users can choose multiple beers and compare them side by side. The top right gives the various avg rankings for appearance, aroma, palette and taste. The bottom left visualization is meant to filter so users can see different beers that are similar to the ones they’ve selected. So if you know you like APAs you can select an APA on the bottom left and the top left viz will show you a bunch of other APAs for you to explore and compare. The bottom right gives the overall average rating for the beers chosen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Clb9k7c0s42sxhn83WfFLw.png" /></figure><p>Perhaps a user likes American Pale Wheat Ales, Belgian Strong Pales and Euro Dark Lagers. By selecting one of each of these different beer types from the bottom left bar chart, the top left visualization filters down to just those beer styles. The individual squares represent specific beers, the size represents popularity (as measured by number of reviews) and the color represents the style. This makes popular beers stand out to the user while also making the difference between beer types obvious.</p><p>The user can also filter for minimum rating and beer style with the filters on the left or even search for a specific beer they like.</p><h3>EARLY RETROSPECTIVE</h3><p>This was a <em>very </em>fun exercise that started as an analysis to find the best beer but evolved into creating a dashboard that consumers would find useful for comparing and discovering new beers. The dashboard certainly still needs multiple iterations to make it user-friendly but in its current form it is still a useful tool for consumers as long as they have a little direction on where to start.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccc698697d58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Analysis — Netflix]]></title>
            <link>https://medium.com/@seanlukeholland/data-analysis-netflix-94fe780dff00?source=rss-f5efeadb387a------2</link>
            <guid isPermaLink="false">https://medium.com/p/94fe780dff00</guid>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[tableau]]></category>
            <category><![CDATA[netflix]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Sean Holland]]></dc:creator>
            <pubDate>Thu, 22 Jun 2023 14:56:03 GMT</pubDate>
            <atom:updated>2023-06-22T15:18:55.860Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Analysis — Netflix</h3><p>This dataset required a lot of modifications to make it useful in order to answer the ultimate question: <strong>What type of content should Netflix produce? </strong>This created other follow up questions that were important for interrogation:</p><ul><li>How can Netflix grow its business?</li><li>How can Netflix increase subscribers?</li></ul><h3>Data Processing and Cleanup</h3><p>From the original data set we can’t really measure what success looks like very well since we have no data on revenue, subscribers, profit, etc.</p><p>The data started with only 12 columns but this ballooned to 20 after separating comma-separated columns into distinct columns for genre and cast members. This would be important for visualizing which genres and actors correlated with success for Netflix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AAHeFtk1Na-eV1ikutL3uQ.png" /><figcaption>Original</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1B8ZdMvEjinh75-Ri8k8cw.png" /><figcaption>Updated</figcaption></figure><p>I also needed to make distinctions for “duration” as this included data types for movies and shows but comparing a 90 minute movie to 3 seasons of “The Office” makes no senses so these were cataloged into separate columns.</p><p>I also added a <a href="https://companiesmarketcap.com/netflix/revenue/">small data</a> set for the following annual data:</p><ul><li>Revenue</li><li>Net Income</li><li>Subscribers</li></ul><p>And joined the data together in tableau to better understand relationships for what drove these metrics.</p><p>I started by creating a word cloud in python for the genres just to get a quick sense of what I might be looking for in the data.</p><pre>import pandas as pd<br>from wordcloud import WordCloud<br>import matplotlib.pyplot as plt<br>import stopwords<br>import openpyxl<br><br>english_stop_words = stopwords.get_stopwords(&#39;english&#39;)<br><br><br># Load the Excel file<br>df = pd.read_excel(r&quot;C:\Users\seanl\My Drive\Data Analysis\Strata Projects\Netflix\datasets\netflix_latest_4_genres.xlsx&quot;)<br><br># Convert the text column to lowercase<br>df[&#39;genre&#39;] = df[&#39;genre&#39;].str.lower()<br><br># Get a list of English stop words<br>stop_words = stopwords.get_stopwords(&#39;english&#39;)<br><br># Define a function to remove stop words from a string<br>def remove_stop_words(text):<br>    if pd.isnull(text):<br>        return &#39;&#39;<br>    return &#39; &#39;.join(word for word in str(text).split() if word not in stop_words)<br><br><br># Apply the function to remove stop words from the text column<br>df[&#39;genre&#39;] = df[&#39;genre&#39;].apply(remove_stop_words)<br><br># Concatenate all the text into one string<br>text = &#39; &#39;.join(df[&#39;genre&#39;])<br><br># Generate a word cloud<br>wordcloud = WordCloud().generate(text)<br><br># Display the word cloud<br>plt.imshow(wordcloud, interpolation=&#39;bilinear&#39;)<br>plt.axis(&quot;off&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*DnYNEw78z7IOy4CEJ2ScIQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*AXkrKijItz7m6vZVcS1IXA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*lOi0RtNZw9KNnBm7w45DnA.png" /></figure><p>I did this for the descriptions of the movies/shows as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*eQc5J_iKWgJUSIJ79LONow.png" /></figure><p>These were a quick way to double check some trends I’d later find in tableau.</p><h3>Analysis — Revenue, Profit and Subscribers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fFRzMrL1zRr9gzGLpqX1Yw.png" /><figcaption>2017 and onward: the golden years for content</figcaption></figure><p>From a content perspective, Netflix really <a href="https://public.tableau.com/app/profile/sean.holland/viz/NetflixUpdated/TypewRevenue?publish=yes">took off in 2017</a>. To better understand trends I kept the preceding few years in most of my analysis.</p><p>In terms of the content Netflix has available, the movie / show mix denoted in the blue/orange bars shows they’ve always leaned more heavily on movies with respect to individual pieces of content. Note this does <em>NOT </em>mean there is more movie content as measured with respect to time / hours of content. So far the number of subscribers tracts almost 1:1 with revenue which makes sense. However, since 2018 shows have been taking market share from movies. But what’s driving new subscriptions?</p><blockquote>Since 2015 subscriber growth has been steady up and to the right with YoY increases between 20–31% — impressive!</blockquote><p>Let’s turn to genres to see how these changed during strong periods of revenue growth.</p><h3><strong>GENRE ANALYSIS — PEAK CONTENT 2017–2021</strong></h3><p>For movies these genres showed up strong on the scene starting in 2017:</p><ul><li>Action &amp; Adventure</li><li>Children &amp; Family Movies</li><li>Comedies</li><li>Documentaries</li><li>Dramas</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R2ZqekvG5GKlBPut827hSw.png" /><figcaption>Movie Genres — YoY % change</figcaption></figure><p>At it’s peak of content in 2019, all of these movie genres (including horror!) made up a LOT of the content on Netflix but most had pulled back by 2021. <em>*Note these and the following show genres were filtered to show those with a minimum of 30 individual titles. Note the numbers reflect YoY %changes.</em></p><p>Meanwhile in the land of TV shows, the following genres were exploding on the scene:</p><ul><li>International</li><li>Crime</li><li>British</li><li>Docuseries</li></ul><p>All followed the same boom/bust nature peaking in 2020 and noticeably pulling back in 2021 (bolstered in 2020 by Reality, Comedies and Anime)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ibQ8qkIjdg-_H3BP8uZMGQ.png" /><figcaption>Show Genres — YoY % change</figcaption></figure><p>We can dive deeper into shows with<strong> season analysis</strong>. Intuitively, more seasons generally means higher audience demand. The longest running shows on Netflix have 9 seasons according to this data set and we certainly see overlap between long-running genre-favorites and overall number of titles making it to at least a 7th season.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*a4Of3R_thL-zTMl0nkygfQ.png" /><figcaption>Average number of seasons: Comedies, Horror, Dramas and Action &amp; Adventure all in the top quartile</figcaption></figure><p>A box and whisker felt intuitive here to understand avg number of seasons for each genre better. The above indicates that the following genres seem to be very popular with audiences starting with the <strong>highest number of seasons:</strong></p><ol><li>Comedies</li><li>Horror</li><li>Dramas</li><li>Action and Adventure</li></ol><p>Conversely, removing the generic “TV Shows”, <strong>the following are</strong> <strong>more likely to be “one-season wonders” and represent potentially more risk</strong> with an allowance for Docuseries which may skew towards a single season by design:</p><ol><li>International</li><li>Reality</li><li>Anime</li><li>Crime</li></ol><p>We’re also under the assumption the longer running shows are less expensive than starting a show from scratch as the up front costs are assumed to be larger. A longer running show also allows Netflix to lock in and better forecast profit and revenue for a certain period of time.</p><h3><strong>COUNTRY ANALYSIS — TV SHOW GENRES</strong></h3><p>I created the following <a href="https://public.tableau.com/app/profile/sean.holland/viz/NetflixUpdated/ShowsDashboard-Geo?publish=yes">dashboard </a>to better understand which countries consume the most TV shows and what genres those are.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OXnZrgNCaI4_1vInRKGAcQ.png" /><figcaption>Largest TV show Markets: USA, UK, Japan and South Korea</figcaption></figure><p><strong>TOP 3 MARKETS — LARGEST NUMBER OF SHOWS</strong></p><ul><li>USA — 760 (28%)</li><li>UK — 213 (8%)</li><li>Japan — 169 &amp; South Korea- 159 tied for 3rd place (6%)</li></ul><p><strong>TOP 3 GENRES — LARGEST NUMBER OF SHOWS</strong></p><ul><li>International — 774</li><li>Crime — 399</li><li>Kids TV — 388</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0p9xT-XnpN5xShXY8FznNA.png" /></figure><p>“International” Is the most popular genre with 774 shows broken down by top three countries:</p><ul><li>South Korea (16%)</li><li>Taiwan (8%)</li><li>India (6%)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IBPOtPis6FCVEztHYkPT4w.png" /><figcaption>Note we’re excluding null values from these analyses (no country listed)</figcaption></figure><p>“Crime” is vastly more popular in the USA than anywhere else with 27% of the total.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lSJVhUoHt-khfKfE8ea30w.png" /><figcaption>USA loves Crime TV</figcaption></figure><p>“Kids TV” is also vastly more popular in the USA as well at a whopping 37% of the total.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FG-6gHsQF5_Q6sOv32iRvQ.png" /><figcaption>USA loves Kids TV</figcaption></figure><p><strong>OTHER NOTABLE TRENDS</strong></p><p>“British TV shows” are most popular in — you guessed it — the UK representing more than 77% of the total!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aByPAGX2hFNC4pz7HBJPNw.png" /><figcaption>The British love British TV. Surprise!</figcaption></figure><p>Lastly and intuitively, “Anime Series” is hugely popular in Japan representing over 74% of the total.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w1bwx5y6-98rEkZbud29gQ.png" /><figcaption>Not surprisingly Japan, the birthplace of anime, consumes the most Anime Series.</figcaption></figure><h3>COUNTRY ANALYSIS —MOVIE GENRES</h3><p>I created a similar <a href="https://public.tableau.com/app/profile/sean.holland/viz/NetflixUpdated/MoviesDashboard-Geo2?publish=yes">dashboard</a> to analyze movies. Relative to shows, movies tend to be <em>dominated</em> by two main markets with the UK a distant 3rd:</p><p><strong>TOP 3 MARKETS — LARGEST NUMBER OF MOVIES</strong></p><ul><li>USA — 2058 (34%)</li><li>India — 893 (15%)</li><li>UK — 206 (3%)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qyq9XqDEY1UBAl9Ov0PsVQ.png" /><figcaption>Reminder: still excluding null values</figcaption></figure><p><strong>TOP ~3 GENRES — LARGEST NUMBER OF MOVIES</strong></p><ul><li>Dramas — 1600 (26%)</li><li>Comedies — 1210 (20%)</li><li>Action &amp; Adventure — 859 (14%)</li><li>Documentaries — 829 (13.5%)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GytyXobxso_KcmEyhiygdg.png" /><figcaption>The USA and India dominate movie content.</figcaption></figure><p>Of the most popular genres, here’s where they are most popular:</p><p><strong>“Dramas” — </strong>almost 50% are represented by just two countries:</p><ul><li>India (24%)</li><li>USA (23.5%)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IksN5tZ27SNwr3BQa0od1g.png" /><figcaption>Documentary popularity is an even split between USA and India</figcaption></figure><p><strong>“Comedies” — </strong>again 50% is represented by just two countries:</p><ul><li>USA (28%)</li><li>India (22%)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WnWvehgVy-Go96cvEAJDvw.png" /><figcaption>Comedy Movies</figcaption></figure><p><strong>“Action &amp; Adventure”</strong></p><ul><li>USA (29%)</li><li>India (15%)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ENewhGuHPXfTIMd3kJR9YA.png" /><figcaption>Action &amp; Adventure movie content dominated by USA</figcaption></figure><p><strong>“Documentaries” — </strong>dominated by the USA</p><ul><li>USA (47%)</li><li>UK (10%)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dOK6k0dW183WrtqxsELzzg.png" /><figcaption>Documentary content also dominated by USA</figcaption></figure><h3>Measures for Success- Returning to Subscribers, Revenue and Profit</h3><p>It’s difficult to parse what variables are driving success given they’ve moved in lockstep for the years of major content growth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*87IOPzfM4gyvppz5UHFcBw.png" /><figcaption>Profit a result of lowered costs?</figcaption></figure><p>However, while subscribers and revenue follow almost identical trajectories, the speed of profit growth noticeably accelerates faster starting in 2017. There were also price increases at the end of 2017 and the beginning of 2019 that likely drove these jumps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MA3uWP0HM-ghuOUaixOEVQ.png" /><figcaption>Profit acceleration from increased revenue?</figcaption></figure><p>Combining increased pricing and lowered costs associated with offering less content starting in 2020, these would likely be the strongest drivers of a steeper profit delta.</p><p>However, it should be noted below that, since 2018, TV shows have been growing in popularity vs movies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RV2XcRm5BUT4VLRQHXKvNA.png" /><figcaption>TV shows (orange) have represented more of the content mix vs Movies (blue) since 2018. (Red line denotes profit)</figcaption></figure><p>And we know that the USA is by far the largest consumer of TV shows representing 28% of the total and that “Crime” and “Kids TV” are by far the most popular genres there. I’d need more data to understand the revenue breakdown by country but if the USA represents any kind of majority then this would lead us towards some suggestions for Netflix that would likely result in continuing this trend of accelerated profit growth.</p><h3>RECOMMENDATIONS FOR NETFLIX</h3><p>Grow the following content segment genres in the USA:</p><ul><li>Crime shows</li><li>Kids TV</li></ul><p><strong>BUT WE NEED MORE DATA!</strong></p><p>There are additional datasets that need to be joined with this analysis to give more specific and insightful recommendations to Netflix. The most important are the following:</p><ul><li>Revenue / Profit breakdown by region — ideally by country</li><li>Subscribers breakdown by region — ideally country</li><li>Revenue / Profit breakdown by subscription type</li><li>Content consumption by subscription type</li><li>IMDB score</li><li>User demographic data</li></ul><p>With these we can really dig into genre trends and which content draws in more subscribers. Revenue, profit and subscribers by country will allow us to understand which countries are seeing accelerated growth and which genres they tend to prefer which would allow Netflix to allocate resources towards those high leverage countries and genres.</p><p>Similarly, understanding the revenue, profit and subscriber breakdown by subscription type can help Netflix formulate strategies to incentivize upgrades. Perhaps a certain type of genre is more popular with Basic subscriptions. Offering more of this type of content for standard plans only could grow revenue by incentivizing an upgrade.</p><p>Lastly, IMDB scores or other scoring metrics are a critical missing piece of the puzzle. Combining this with the number of seasons analysis would be a powerful way for Netflix to predict which type of show or movie will be the next “Game of Thrones” or some other wildly popular, long-running show.</p><h3>EARLY RETROSPECTIVE</h3><p>This project was an exercise in patience and demonstrated the advantage of having domain knowledge when drawing data insights. There were a TON of gaps in this data and I found myself going back and forth between the original data in Excel and Tableau and reconfiguring/formatting the data differently on multiple occasions which can get messy and lead to inconsistencies and errors. This process went on longer than I would have preferred as it became clear while doing the analysis that any recommendations to Netflix would likely hinge on income statement performance which is tied to directly to number of subscribers.</p><p>I didn’t find much use for the director or cast member data — the relationship between those and typical KPI’s was too abstract but perhaps someone with more domain knowledge would better understand what to do with that data. That’s not to say there aren’t interesting insights there — Rajiv Chilaka is a <em>prolific </em>director while Shah Rukh Khan holds the record for appearing in the largest number of movies at 26!</p><p>If I were to start over the first major call-out and subsequent action item would be to understand that, without KPI data it’s hard to make recommendations and so the <em>first </em>step should have been to seek out and combine this with the original data set. Without the requisite domain knowledge though, it’s important to stay humble and understand that the data exploration process will be bumpy and changes are almost inevitable. Documenting these changes and why they’re being made is the most important part so that other stakeholders can understand the process and I can go back in a month or a year and jump quickly back into it if needed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94fe780dff00" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Baby Names — Data Analysis]]></title>
            <link>https://medium.com/@seanlukeholland/baby-names-data-analysis-961bf067dfef?source=rss-f5efeadb387a------2</link>
            <guid isPermaLink="false">https://medium.com/p/961bf067dfef</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[tableau]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Sean Holland]]></dc:creator>
            <pubDate>Thu, 04 May 2023 15:48:30 GMT</pubDate>
            <atom:updated>2023-05-09T14:38:28.385Z</atom:updated>
            <content:encoded><![CDATA[<h3>Baby Names — Data Analysis</h3><p>So what can we learn about baby name trends between 1910 and 2021 in the USA?</p><p>To start, we need to do some data transformation. 50 different text files isn’t very useful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FxjL4U4fgEW64fvF" /><figcaption>Babies — they have names!</figcaption></figure><h3><strong>DATA TRANSFORMATION PROCESS</strong></h3><p>Note that names that had less than five occurrences in a given year were not included in this data set.</p><p>The 50 different files represent the 50 United States but these individual files need to be analyzed together to create more meaningful insights so let’s use the following python libraries and import:</p><ul><li>os</li><li>pandas</li><li>xlsxwriter</li></ul><p>We’ll combine all of the data into a single excel workbook with a separate sheet for each state:</p><pre># Set the directory path<br>path = &quot;C:\\Users\\seanl\\My Drive\\Data Analysis\\Strata Projects\\babynames\\datasets&quot;<br><br># Get a list of the file names in the directory<br>file_names = os.listdir(path)<br><br># Filter the list to only include files with state abbreviations in the name<br>valid_states = [&quot;AL&quot;, &quot;AK&quot;, &quot;AZ&quot;, &quot;AR&quot;, &quot;CA&quot;, &quot;CO&quot;, &quot;CT&quot;, &quot;DE&quot;, &quot;FL&quot;, &quot;GA&quot;, &quot;HI&quot;, &quot;ID&quot;, &quot;IL&quot;, &quot;IN&quot;, &quot;IA&quot;, &quot;KS&quot;, &quot;KY&quot;, &quot;LA&quot;, &quot;ME&quot;, &quot;MD&quot;, &quot;MA&quot;, &quot;MI&quot;, &quot;MN&quot;, &quot;MS&quot;, &quot;MO&quot;, &quot;MT&quot;, &quot;NE&quot;, &quot;NV&quot;, &quot;NH&quot;, &quot;NJ&quot;, &quot;NM&quot;, &quot;NY&quot;, &quot;NC&quot;, &quot;ND&quot;, &quot;OH&quot;, &quot;OK&quot;, &quot;OR&quot;, &quot;PA&quot;, &quot;RI&quot;, &quot;SC&quot;, &quot;SD&quot;, &quot;TN&quot;, &quot;TX&quot;, &quot;UT&quot;, &quot;VT&quot;, &quot;VA&quot;, &quot;WA&quot;, &quot;WV&quot;, &quot;WI&quot;, &quot;WY&quot;]<br>state_files = [file for file in file_names if file.endswith(&quot;.TXT&quot;) and file[:2] in valid_states]<br>print(&quot;All files:&quot;, file_names)<br>print(&quot;State files:&quot;, state_files)<br><br>print(f&quot;Found {len(file_names)} files in directory&quot;)<br>print(f&quot;Filtered {len(state_files)} state files&quot;)<br><br># Create an empty dictionary to store the data from each file<br>data_frames = {}<br><br># Loop through each file, read it into a Pandas DataFrame, and add the DataFrame to the dictionary<br>for i, file in enumerate(state_files):<br>    file_path = os.path.join(path, file)<br>    df = pd.read_csv(file_path, sep=&#39;,&#39;)<br>    data_frames[f&#39;Sheet{i+1}&#39;] = df<br><br># Check if there are any DataFrames to concatenate<br>if len(data_frames) == 0:<br>    print(&quot;No DataFrames to concatenate!&quot;)<br>else:<br>    # Write the DataFrames to a single Excel file with multiple sheets<br>    writer = pd.ExcelWriter(&#39;combined_data.xlsx&#39;, engine=&#39;xlsxwriter&#39;)<br>    for sheet_name, df in data_frames.items():<br>        df.to_excel(writer, sheet_name=sheet_name, index=False)<br>    writer.save()</pre><p>I then tried to use python to loop through the sheets to append a header for each sheet:</p><pre>import openpyxl<br>import os<br><br># Set the directory path<br>path = &quot;C:\\Users\\seanl\\My Drive\\Data Analysis\\Strata Projects\\babynames\\Combined Data&quot;<br>file_name = &quot;cd.xlsx&quot;<br><br># Load the workbook<br>wb = openpyxl.load_workbook(os.path.join(path, file_name))<br><br># Define headers<br>headers = [&quot;state&quot;, &quot;sex&quot;, &quot;year&quot;, &quot;name&quot;, &quot;count&quot;]<br><br># Add headers to each sheet<br>for sheet_name in wb.sheetnames:<br>    print(f&quot;Processing sheet: {sheet_name}&quot;)<br>    ws = wb[sheet_name]<br>    ws.insert_rows(0)<br>    for idx, header in enumerate(headers, start=1):<br>        cell = ws.cell(row=1, column=idx)<br>        cell.value = header<br><br>print(&quot;Saving workbook with headers...&quot;)<br>wb.save(os.path.join(path, &#39;baby_names_with_headers.xlsx&#39;))<br>print(&quot;Workbook saved as &#39;baby_names_with_headers.xlsx&#39;&quot;)<br></pre><p>However, this was unsuccessful and so I went into excel directly to write a VBA script to accomplish this instead:</p><pre>1. Sub InsertColumnNames()<br>2.     Dim ws As Worksheet<br>3.     Dim rng As Range<br>4.     <br>5.     For Each ws In ThisWorkbook.Worksheets<br>6.         Set rng = ws.Range(&quot;A1:E1&quot;)<br>7.         rng.Value = Array(&quot;State&quot;, &quot;Sex&quot;, &quot;Year&quot;, &quot;Name&quot;, &quot;Count&quot;)<br>8.     Next ws<br>9. End Sub</pre><p>After I’d realized I’d already modified the first 5 sheets I modified the code as follows:</p><pre>1. Sub InsertColumnNames()<br>2.     Dim ws As Worksheet<br>3.     Dim rng As Range<br>4.     Dim i As Integer<br>5.     <br>6.     i = 1<br>7.     For Each ws In ThisWorkbook.Worksheets<br>8.         If i &gt; 5 Then<br>9.             Set rng = ws.Range(&quot;A1:E1&quot;)<br>10.             rng.Value = Array(&quot;State&quot;, &quot;Sex&quot;, &quot;Year&quot;, &quot;Name&quot;, &quot;Count&quot;)<br>11.         End If<br>12.         i = i + 1<br>13.     Next ws<br>14. End Sub</pre><p>I also wrote a python script to load the data into MySQL Workbench but this was unsuccessful and so I decided to load the data into Tableau instead for further analysis by unioning all the separate sheets together. I’ve often found that loading large datasets into MySQL Workbench is more trouble than it’s worth, even though there are various functionality preferences specific to SQL that would be helpful with this data set. I may explore a different SQL IDE.</p><h3><strong>INSIGHTS</strong></h3><p>What is the most popular name of all time?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*99XIOeeN0HfGIB2xRvZH9Q.png" /></figure><blockquote><strong>James </strong>has over 5M occurrences while <strong>Mary</strong> was the most common female name with 3.7M occurrences and ranked 6th overall.</blockquote><p>Outside of Mary, the top 14 names of all time were all traditionally male names. This naturally prompted the question of <em>why </em>there were so many male names at the top.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tdLZ7VpSUGXUYknghmb3vQ.png" /><figcaption>Females had 50% more distinct names vs Males</figcaption></figure><p>Males represented about 52% of the total population meaning there was a relatively smaller number of unique names distributed across a larger population — a likely explanation for the concentration of male names at the top of the number of occurrences.</p><h3><strong>CHANGES IN POPULARITY — 1980 to 2021</strong></h3><blockquote><strong><em>Mateo </em></strong><em>had the largest percentage increase in popularity with a whopping 151,000% increase but note this was an increase from a small base. Similarly </em><strong><em>Luna </em></strong><em>was almost a 136,000% increase.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*T8uKw7XOK9PpRwMjMQKcTQ.png" /></figure><p>On the flip side for names that had fallen the most in popularity there were plenty that dropped 100% so it felt useful to filter these as names that dropped by a <strong>minimum aggregate of at least 5,000 occurrences</strong>. Which yielded the following:</p><h4><strong>Popularity — Percentage Decreases Top 3</strong></h4><p><strong>MALES</strong></p><ul><li>Scott -97% (-12,851)</li><li>Brian -96% (-27,444)</li><li>Jeffrey -96% (-15,628)</li></ul><p><strong>FEMALES</strong></p><ul><li>Kristin -100% (-7,660)</li><li>Misty -100% (-5,523)</li><li>Brandy -100% (6,374)</li></ul><h4>Popularity — Aggregate Decreases Top 3</h4><p><strong>MALES</strong></p><ul><li>Michael (-59,000)</li><li>Jason (-45,000)</li><li>Christopher (-43,000)</li></ul><p><strong>FEMALES</strong></p><ul><li>Jennifer (-58,000)</li><li>Amanda (-35,145)</li><li>Jessica (-33,205)</li></ul><h3><strong>GENDER AMBIGUITY</strong></h3><p>In order to find the most gender ambiguous names, we need to define gender ambiguity in a way that tableau understands. I started with a calculated field called “Gender Ratio”</p><blockquote>ABS(SUM(IF [Sex] = “M” THEN 1 ELSE 0 END) / SUM([Count]) — 0.5)</blockquote><p>A value of 0 would then be a perfectly ambiguous name while .5 is the least ambiguous.</p><p>Ranking these the most gender ambiguous names in the set had Gender Ratios of .3 and there were quite a lot of them so I filtered for names that had at least 10,000 occurrences. It did seem odd that a vast number of names clumped towards .3 and that this value represented a lower bound. This was my first indication there might be a problem with the data or my calculations.</p><p>To make more sense of the data, I started filtering based on the number of occurrences. I also discovered that, while the gender ratio calculated field I created was useful for gender ambiguity across the entire timeframe, it needed additional fine-tuning to understand gender ambiguity in any specific year. I discovered this after checking the data in excel to confirm that insight from tableau that “Riley” was indeed the most gender ambiguous name from 1945 with at least 100 occurrences.</p><pre>Sub FilterAndOutput()<br>    Dim ws As Worksheet<br>    Dim outputWs As Worksheet<br>    Dim lastRow As Long<br>    Dim outputRow As Long<br>    <br>    &#39; Create a new worksheet for the output<br>    Set outputWs = ThisWorkbook.Worksheets.Add<br>    outputWs.Name = &quot;Output&quot;<br>    <br>    &#39; Set up the header row in the output sheet<br>    outputWs.Cells(1, 1).Value = &quot;State&quot;<br>    outputWs.Cells(1, 2).Value = &quot;Sex&quot;<br>    outputWs.Cells(1, 3).Value = &quot;Year&quot;<br>    outputWs.Cells(1, 4).Value = &quot;Name&quot;<br>    outputWs.Cells(1, 5).Value = &quot;Count&quot;<br>    <br>    &#39; Initialize the output row<br>    outputRow = 2<br>    <br>    &#39; Loop through all worksheets in the workbook<br>    For Each ws In ThisWorkbook.Worksheets<br>        &#39; Skip the output sheet<br>        If ws.Name &lt;&gt; &quot;Output&quot; Then<br>            &#39; Find the last row in the current sheet<br>            lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row<br>            <br>            &#39; Loop through all rows in the current sheet<br>            For i = 2 To lastRow<br>                &#39; Check if the criteria are met (name = Riley, year = 1945)<br>                If ws.Cells(i, 4).Value = &quot;Riley&quot; And ws.Cells(i, 3).Value = 1945 Then<br>                    &#39; Copy the row to the output sheet<br>                    ws.Rows(i).Copy Destination:=outputWs.Rows(outputRow)<br>                    <br>                    &#39; Increment the output row<br>                    outputRow = outputRow + 1<br>                End If<br>            Next i<br>        End If<br>    Next ws<br>End Sub</pre><p>The results were not as expected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*Q7S4SvGXWPUtpo66ALZFYw.png" /><figcaption>No F’s to be found…</figcaption></figure><p>So tableau was saying Riley is the most gender ambiguous…</p><p>while the core dataset from excel showed the exact opposite…</p><p>So I added another gender ratio calculated field in combination with name and year but made sure to include the gender ratio calculated field in the rows section and sorted names based on that criteria ascending.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*vInbdUabkYb_0daW7ma_TQ.png" /></figure><p>It turned out after going back into excel that our initial gender ratio calculation needed modification as it was calculating this ratio for every row when it should have been totaling males and females per year and then giving a ratio. I created two more calculated fields for COUNT(males) and COUNT(females) and used these as building blocks for a new calculated field to calculate the gender ratio:</p><p><em>ABS(SUM([Male Count]) / (SUM([Male Count]) + SUM([Female Count])) — 0.5)</em></p><p>FINALLY it appeared we have accurate information and double checking the excel data confirmed as much.</p><p>0 = Perfectly Ambiguous (Male count = Female count)</p><p>.5 = Perfectly Homogenous (0 Males OR 0 Females)</p><h3><strong>MOST GENDER AMBIGUOUS NAMES — 1945</strong></h3><ul><li>Maxie — 0</li><li>Artie — .011</li><li>Lavern — .014</li></ul><h4>MOST GENDER AMBIGUOUS NAMES — (minimum 100 occurrences)</h4><ul><li>Leslie — .073</li><li>Guadalupe — .088</li><li>Johnnie — .143</li></ul><h3>MOST GENDER AMBIGUOUS NAMES — 2013</h3><ul><li>Arlin — 0</li><li>Cree — 0</li><li>Devine — 0</li></ul><h4>MOST GENDER AMBIGUOUS NAMES — (minimum 100 occurrences)</h4><ul><li>Charlie — .17</li><li>Riley — .33</li><li>Hayden — .33</li></ul><p>Notably, when filtering for a minimum of 500 occurrences for the entire time series the names “Infant” and “Baby” appeared on the radar as the most ambiguous.</p><h3>EARLY RETROSPECTIVE</h3><p>This has been a great way to flex a lot of different data muscles including Excel, VBA macros, python scripts and tableau visualizations. The gender ambiguity problem persisted for longer than I’d prefer but was an<em> excellent</em> exercise in staying vigilant and rigorous with respect to data integrity and accuracy: a perfect example of avoiding GIGO <em>(Garbage In Garbage out).</em></p><p>The next steps will be combining more interesting visualizations into dashboards with tableau to be able to view the data from different and new perspectives.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=961bf067dfef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Superstore Data Set — Analysis Through Exploration]]></title>
            <link>https://medium.com/@seanlukeholland/superstore-data-set-analysis-through-exploration-e97b99f6cb62?source=rss-f5efeadb387a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e97b99f6cb62</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[tableau]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Sean Holland]]></dc:creator>
            <pubDate>Fri, 20 Jan 2023 22:09:32 GMT</pubDate>
            <atom:updated>2023-01-23T21:16:50.752Z</atom:updated>
            <content:encoded><![CDATA[<h3>Superstore Data Set — Analysis Through Exploration</h3><p>I’m going to start with a couple conclusions I drew and then explore the (sometimes meandering) path I took to get to these insights. I was able to come up with some actionable and fairly specific recommendations based on the rather well-known Superstore data set which contains about 10,000 rows of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/0*Ga5EP25684nKsGTd.png" /></figure><h3>RECOMMENDATIONS — INVENTORY MANAGEMENT</h3><ol><li>Route more binders and machines away from PA, OH, IL, CO and TX as these represent some of the lowest (negative) profit items in these states</li><li>Route these binders and machines to NY and CA where they represent some of the MOST profitable subcategories</li><li>To reduce shipping time and cost, ship specifically from PA, OH and IL to NY.</li><li>Similarly, to reduce ship time and cost, ship binders and machines from TX and CO to CA.</li></ol><figure><a href="https://public.tableau.com/app/profile/sean.holland/viz/Superstore12_16741670446570/SarDash"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*02xDMuo2dOEgNZKTURxQVA.png" /></a></figure><h3>RECOMMENDATIONS — DISCOUNTS</h3><ol><li>STRONG CANDIDATES for linear (similar)<strong> increase</strong> in discount from previous year (2014): Copiers, Accessories, Paper</li><li>WEAK CANDIDATE for similar <strong>decrease</strong> in discount from 2014: Tables</li></ol><figure><a href="https://public.tableau.com/views/Superstore11_16725968129540/NewestDash?:language=en-US&amp;:display_count=n&amp;:origin=viz_share_link"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xEVYWknfBn_wHwOLeIeg8Q.png" /></a></figure><h3>The Process</h3><p>Throughout all visualizations I felt it was important to stay as consistent as possible with coloration which is why the orange/blue profit dynamic was used on both dashboards.</p><p>Here’s one of the most important lessons I learned throughout this process:</p><blockquote><strong>If you want <em>real insights </em>from your data, <em>dashboards are superior to individual visualizations.</em></strong></blockquote><p>Here’s why:</p><ul><li>Filtering and highlighting empower the user to see small (or large) slices of data</li><li>The user can choose which pieces of data they want to see and most importantly -</li><li>They can see the data in a <em>multi-dimensional</em> way <em>simultaneously</em></li></ul><figure><a href="https://youtu.be/Sg14jNbBb-8?t=3"><img alt="" src="https://cdn-images-1.medium.com/max/762/1*DeWuTo2gkqPPSJYlHZc1ZA.png" /></a></figure><p>This was the key to finding virtually all of my recommendations. For example, when selecting a state it’s obvious there are two standout high-profit states (CA and NY) and filtering with these made it again immediately obvious which subcategories were most profitable. I used the same visual cues to discover the least profitable states and categories and I added individual zip codes to order to narrow down precisely which stores should get less of one product and more of another.</p><p>I’m not a supply-chain expert so I would need to consult domain experts to get their specific opinions on these recommendations. However, I feel confident if these domain experts were my stakeholders that I could tailor these dashboards further to be even more precise with my recommendations.</p><p>Ship time is another dimension that I may add in the future as I feel it will be relevant to the recommendations related to which products should be going to which zip codes.</p><h3>Finding the relevant relationships</h3><p>This process required a lot of trial and error and in a professional setting it’s likely I’d already know or quickly be able to access these relationships. Nonetheless it was fun to iterate through and isolate important relationships.</p><figure><a href="https://public.tableau.com/app/profile/sean.holland/viz/SuperstoreProfSalesQuadrants/ProjectDash1?publish=yes"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WKZfbCOZWQSFxfX5yR2iWg.png" /></a></figure><p>I started with the sales/profit relationship for the various product subcategories with this thesis: <em>can we increase sales of the bottom right quadrants to increase profit</em>? <em>Should we consider reducing sales of products in the top left quadrant?</em> I added annotations to help the user understand the <em>why </em>behind this.</p><p>The region filter on the right still needs some tweaks as of January 2023 as it’s not working as intended. The quantity sold at the bottom was meant to specifically understand which way the trend was already headed.</p><p>Based on this hypothesis we might actually consider shipping and selling less machines but that would be a mistake. Even as I write this I know from the geographic dashboard data that this isn’t the whole story so I’ll be adding a subcategory filter to that dashboard.</p><figure><a href="https://public.tableau.com/app/profile/sean.holland/viz/Superstore12_16741670446570/SarDash?publish=yes"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*idC-yNx5JI2tmSjwZgoZCw.png" /></a><figcaption>Filtering to only see Machines</figcaption></figure><p>There we go! Wow, that’s a lot of variance. I may have to make ANOTHER dashboard to explore the level of variance for each product in the future.</p><p>Clearly though we don’t want to just reduce machine shipments across the board. We can see there’s some highly negative profitability in states like OH and PA but also some some very HIGH profitability in states like NY and they happen to be right next to each other. Logically then we’d want to send less machines to OH/PA and more to nearby NY. We’d have to dig deeper or consult domain experts to get estimates of the delta there but the point is, as I explored the data new questions were <em>constantly arising.</em></p><p>Just like individual visualizations only give a small piece of the story, we know there’s utility in using different dashboards simultaneously which brings me to this beauty:</p><figure><a href="https://public.tableau.com/app/profile/sean.holland/viz/Superstore11_16725968129540/NewestDash"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xEVYWknfBn_wHwOLeIeg8Q.png" /></a><figcaption>What’s the relationship between discount and profit?</figcaption></figure><p>It looks like a bit of a mess so this one requires a bit of direction for the user which is why I added the note about r-squared. The upper right visualization is the key to understanding whether there’s a strong relationship between discount and profit. This is important as discount is something we can directly control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HJlSe8_6cxrpyjwgXCMsig.png" /><figcaption>Looking for high r-squared</figcaption></figure><p>I created the actions on the dashboard so that users can filter directly from either of the top two visualizations <em>or </em>accomplish the same filtering using the subcategory drop down on the top right. Having both in place felt intuitive. Filtering with the top left viz for profit, we can start with our most profitable subcategory, copiers, to instantly see some important information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nBPV1ZeZFhMnZ84BqExA3g.png" /><figcaption>Data on JUST copiers</figcaption></figure><p>The top right viz shows an r-squared of .84 meaning there’s a strong relationship between discount and profit for copiers. The bottom visualization is meant to help the user decide what kind of increase (or decrease) in discount would be appropriate. I played around with adding the sales vs discount relationship over time to further inform this decision but it made the dashboard a bit cluttered. We can see a relatively linear increase in discount leads to a similar linear increase in profit, so it’s fair to recommend a similar, linear increase in discount going into next year.</p><p>Does discount itself drive profit? Or does it have a larger impact on sales which <em>then </em>affects profit?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H7quv5MqS_FqNPN5ans8hw.png" /><figcaption>Sales vs Discount over time</figcaption></figure><p>It appears from the above graphic the delta between discount and sales is &gt;1 meaning a $1 increase in discount may drive a $1.1 or $1.2 increase in sales.</p><p>Let’s add in quantity sold over time to get a clearer picture of this relationship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UTBYSGOfBxGDrG97aHXF_w.png" /></figure><p>For 2012 and 2013 we see increases in quantity of ~10% and ~6% respectively. Since the corresponding discount deltas are significantly larger than that and the sales deltas are even larger still, we appear to be driving higher prices in a non-linear fashion which is corresponding to a nice linear increase in profit.</p><p>So we have some powerful tools here for the user to make informed discount decisions for next year as well as how many units we may want to ship.</p><h3>Early Retrospective</h3><p>I’ve been working with the data set for about a month now and here’s what I’ve discovered:</p><ul><li>Gut instincts are useful during the exploration phase</li><li>Tableau enhances these instincts and turns them into</li><li><em>Actionable insights</em></li></ul><blockquote>There is beauty in taking 10,000 data points and distilling it down into just a few actionable insights.</blockquote><p>In order to offer some truly precise recommendations we need to add in some statistical software on our data analysis journey.</p><p><em>Pandas, NumPy and R have entered the chat.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e97b99f6cb62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Analysis — Cyclistic Bike Share]]></title>
            <link>https://medium.com/@seanlukeholland/cyclistic-bike-share-case-study-8a9d7441bfec?source=rss-f5efeadb387a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a9d7441bfec</guid>
            <category><![CDATA[bikeshare]]></category>
            <category><![CDATA[chicago]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[tableau]]></category>
            <dc:creator><![CDATA[Sean Holland]]></dc:creator>
            <pubDate>Tue, 13 Dec 2022 16:34:30 GMT</pubDate>
            <atom:updated>2024-04-05T16:18:42.457Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part II can be found (</em><a href="https://medium.com/@seanlukeholland/cyclistic-bike-share-part-ii-pricing-analysis-7dcad9d4702b"><em>here</em></a><em>) and contains scenario analysis recommendations to guide marketing spend and project ROI.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rj8DGHuKlX9L9Z2IctmAJw.png" /></figure><p>Scenario: A bike share company (Cyclistic) in Chicago has asked its data team to deliver insights into the <strong>different ways consumers use their bike share program</strong>. There are two groups of users:</p><ul><li><strong><em>casual riders</em></strong> who purchase single-ride or full-day passes and</li><li><strong><em>members</em></strong> who pay a monthly or annual fee for unlimited rides.</li></ul><p>Since members are much more profitable, the director of marketing, Lily Moreno, wants to better understand these two groups and <strong>how their bike usage differs</strong>. Using this data, Cyclistic wants to <strong>create compelling digital marketing campaigns to convert casual riders into members.</strong></p><p>The following gives an overview of how I accomplished the following:</p><ul><li>Obtained user ride data</li><li>Cleaned and manipulated the data</li><li>Analyzed the data with Excel and Tableau</li><li>Gathered insights</li><li>Provided recommendations to the Cyclistic marketing team and</li></ul><h3>Data Reliability</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CNsR6gdlVCgVCE5CECz8Hg.png" /></figure><p>The data source itself was already given with the case study. Credibility wasn’t an issue since it came directly from Cyclistic who has a vested financial interest in the accuracy of the data.</p><p>The data came in monthly excel files ranging from November of 2021 to October of 2022.</p><p>Next came processing and cleaning as well as a little manipulation.</p><h3><strong>Excel</strong></h3><p>Since there were about 5.5M rows of data spread across 12 tabs (each tab representing a month of data) using pivot tables and doing lots of analysis on Excel itself was unwieldy and would have been time consuming. It was, however, handy for some basic cleaning to discover irregularities or inconsistencies:</p><ul><li>Conditional formatting to calculate missing fields</li><li>Removing duplicates</li><li>Additional ride length data calculation</li></ul><p>I discovered small percentages (~1.5%) of dock station names missing as well as a bike-type (docked) that seemed out of place so in the port to tableau that data was purposefully filtered out. Because it was such a small portion of the data it did not have a heavy impact on the analysis or findings.</p><p>I also used the =MINUTE() function and a custom formula to calculate ride length: = IF(end minute &lt; start minute, 60-ABS(end minute — start minute), ABS(end minute — start minute))</p><p>Every large change or filter that I used was saved into a new data set in order to go back to the original set if needed.</p><h3>Tableau</h3><p>Since I don’t have a paid version of tableau, I couldn’t port the data to SQL to combine it into one large data set. To get around this, I used the <em>union </em>function when manipulating the data source after it was ported. This was slow but still manageable requiring about 10 minutes of load time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*1-I-74iGu8USIYB7DJbWPg.png" /></figure><p>One of the best things about Tableau visualizations is it becomes obvious when there’s inconsistent or incorrect data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*XVVXYHal6d8GASLWt5U_Cg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*fSOFf9URwiTOJSjz_jyHlA.png" /><figcaption>Inconsistent data becomes obvious and easy to filter out</figcaption></figure><p>When looking for incorrect data points the map locations became immediately obvious. Adding color shading as a visual cue for ride numbers was also an important step for filtering out inconsistent data. Double checking the total rides in these locations against the excel calculations made it clear that Tableau was aggregating blank Station Name data into these points and so they were filtered out.</p><p>From here I was able to do the heavy lifting of the analysis itself with many key findings differentiating members from casuals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ppAKXu7tURFGKw9o3rBLOw.png" /><figcaption>Members out-ride casuals 3:2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*49XvHH0vbnGGRozSbkc4sA.png" /><figcaption>Casuals prefer electric bikes</figcaption></figure><p>Tableau is an <em>excellent </em>tool for discovering insights and finding trends that would otherwise be hidden. Given the data structure and Tableau’s powerful visualization and drill-down filtering capabilities it was easy to create a profile of the ways the two groups used Cyclistic bike share bikes.</p><p>One of the key findings was <strong>casual rider’s preference for electric bikes.</strong></p><p>It was also important to understand where the two groups preferred to ride and when.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TIGuTMX04uKaEcw0r1s2bg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iIqN4OoF8FuHSq5BBRRZVg.png" /><figcaption>Casuals prefer being near the water and the Loop while Members skew further West with a Hyde Park Oasis far to the South</figcaption></figure><p>To understand where people rode the bikes I used bar charts and filtered for top locations using light/dark contrast to make it more obvious which stations were preferred by the two cohorts. I also added a map to visualize these locations.</p><p>One of the best features in tableau is the ability to create subsets and filter on those sets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*lh5G5idGZvXjiHUZGSnsQw.png" /></figure><p>Using sets it became easier to isolate certain high-traffic locations for the two cohorts. It would also become important later when targeting certain groups for marketing campaigns. Lastly, it’s easy to create sets to filter out the bad data for future visualizations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MUG5D8zyxKl8W7mtZQPMvw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1IQkm1SuCoX_CarFf1xH9w.png" /></figure><p>From there it was important to drill down into cyclicality as Chicago gets extremely cold in the winter and generally experiences a good amount of snow which makes riding conditions more hostile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F9IqV9j28qPTiBut-6G1yQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O5I6sZHXmizfjCyHeiVqbA.png" /><figcaption>Visualizing total rides and the converting to a % basis between the two cohorts helps further understand their different usage styles</figcaption></figure><p>For certain stakeholders it’s important to know total ride numbers but for others it’s more important to understand the relationship in percentage terms. For example, total rides are important for Cyclistic’s financial analysts who need to understand total revenue and profit. This is important for marketing as well but it’s also important for marketing to understand the % relationship to better target the casual cohort or more specific subsets. Part of this became the basis for the <em>“Convertible Casuals” </em>that would be the target audience for a potential marketing campaign which we’ll dive into later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q5tWc8WAnAa6yWiUcUGnfg.png" /><figcaption>Casuals surge during weekends…</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1dUtc2hPkB7doqAY4ZcniQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zJdEL6DHLd1HTeE6JouEPQ.png" /><figcaption>…while members skew towards weekdays and commuter hours</figcaption></figure><p>Drilling down further on daily and hourly usage are important for building the different cohort’s profiles as well as informing digital marketing campaign targeting. The data shows that during commuter hours, up to 80% of riders will be members on any given day. Broadly speaking, if we want to target casuals we’d prefer messaging to be consistent with their heavier ridership in the 12–6pm time frame.</p><p>Overall usage tends to steadily rise throughout the day and peaks around the end of the work day at 5pm for both cohorts but casuals still have a fairly strong presence in the evening and tend to outnumber members later in the evening.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XsTwuGEiZ2A_cUJ1tgv6Lg.png" /></figure><p>There was a noticeable difference in ride length between the two groups:</p><ul><li>Casuals averaged 16 minutes per ride</li><li>Members averaged under 12</li></ul><p>For my own analysis it was useful to create some dashboards with highlighting capabilities to focus on specific groups of users and locations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w8K2PxBJq0l5p2pyZR6JCg.png" /><figcaption>Side by side comparison of Casuals and Members busiest ride locations</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cfp82MG9ZhRqI6jcDlbW3w.png" /><figcaption>Highlighting certain locations</figcaption></figure><h3><strong>Insights</strong></h3><p>From the previous analysis it became clear that casuals had the following preferences…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GWdlxBoC-s1Nuo8rZ9OafA.png" /></figure><p>… and thus it was fair to extrapolate the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ag49arkiHENRCC1ZAix7Zg.png" /></figure><p>While members had the following characteristics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wYOQoF392CT5dDxAV-3gHg.png" /></figure><p>With these profiles in hand I could now start drilling down further into the top casual locations and created a subset of riders I dubbed the <em>Convertible Casuals.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WQ1FFWqr8MNQ_yn2C_z4kA.png" /><figcaption>Convertible Casuals Dashboard — top locations and favorite months to ride</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ijJBhQCHvmloONJN2yM2fA.png" /><figcaption>Who’s most likely to convert to a member?</figcaption></figure><p>I chose this group specifically for several reasons:</p><ul><li>The bulk of casual riders during peak months (May — September) are more likely to be tourists</li><li>Tourists will be very hard to convert into members given their transient nature so we’ll filter them out of our target audience</li><li>March, April and October through December casual riders still account for a sizeable cohort of 600k rides or 10% of <em>all total annual ridership</em></li><li>These riders are <em>less </em>likely to be tourists and so conversion rates are likely to be higher</li><li>They’re willing to ride during colder months or in harsh riding conditions</li></ul><p>So if we’re trying to convert this group to members and we know casual riders prefer electric bikes we can now use that as the basis for our marketing campaign.</p><h3><strong>Recommendations to the Cyclistic marketing team</strong></h3><p>The basis for this marketing campaign would be <em>making electric bike usage easier for members.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qUpSxpGLbgzBw037qI3bIA.png" /></figure><p>This makes both commuting and pleasure riding more favorable for members by offering several or all of the following advantages to members:</p><ul><li>Add electric bikes to member-heavy downtown locations, especially the ones near casual-heavy stations in River North, Gold Coast and near the water and Loop</li><li>Make usage and docking / undocking frictions more seamless for Members</li><li>Incentivize membership with short term or signup discounts in the cold months</li><li>Decrease cost of electric bikes for members</li></ul><h3><strong>Early Retrospective</strong></h3><p>Given it’s innate ability to quickly visualize, customize, filter and drill down, <strong>Tableau once again was my tool of choice for the majority of the analysis</strong>. It also works in tandem with the data cleaning process in excel as it makes bad data visually obvious and this can be further interrogated using excel.</p><p>Where Tableau falls short is in creating custom functions to create NEW data. While it has this capability, it’s much more clunky and less intuitive than Excel. I found myself taking much longer periods of time trying to create a function to calculate ride length in Tableau and finally realized that it’s just better suited for Excel.</p><p>Understanding SQL and how unions work (and how they differ from joins) was also key for combining the 12 different data sets. This particular set contained about 5.5M rows and 16 columns which I’d say is the outer limit for Tableau’s usefulness with the version that I currently use. With 10 minute load times it’s a huge hassle to have to flip back and forth between the data source and the visualizations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a9d7441bfec" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>